6

I am trying to get my head around PFRelation in parse. I have a class called "girlBio" that stores information about girls and a class called "stuff" that stores information about items. code below:

PFObject *item = [PFObject objectWithClassName:@"stuff"];
item[@"Name"] = @"PS3";
PFObject *girl = [PFObject objectWithClassName:@"girlBio"];
girl[@"Name"] = @"Jessica";
PFObject *girl2 = [PFObject objectWithClassName:@"girlBio"];
girl2[@"Name"] = @"Cindy";

PFRelation *relation = [item relationForKey:@"owners"];
[relation addObject:girl];
[relation addObject:girl2];
[item saveInBackground];

--------------------------------- update also tried this -------------------------

PFObject *item = [PFObject objectWithClassName:@"stuff"];
item[@"Name"] = @"PS3";
PFObject *girl = [PFObject objectWithClassName:@"girlBio"];
girl[@"Name"] = @"Jessica";
[item saveInBackground];
[girl saveInBackground];
PFRelation *relation = [item relationForKey:@"owners"];
[relation addObject:girl];
[item saveInBackground];

So I want this item to be owned by several girls however when I run the program I get this error:

Error: can't add a non-pointer to a relation (Code: 111, Version: 1.6.0)

Can someone help please?

Thank you

Kex
  • 8,023
  • 9
  • 56
  • 129

1 Answers1

8

You need to save your objects girl1 and girl2 before saving the relationship. Otherwise, even thought your local copy knows about them, the server does not.

UPDATE

You also need to make sure the saves for girl1 and girl2 and item complete before you save the relation. However, you probably don't want to run these saves on the primary thread, so I'd recommend something like this (which I just ran without issue):

dispatch_async(dispatch_get_main_queue(), ^{
    PFObject *item = [PFObject objectWithClassName:@"stuff"];
    item[@"Name"] = @"PS3";
    PFObject *girl = [PFObject objectWithClassName:@"girlBio"];
    girl[@"Name"] = @"Jessica";
    [item save];
    [girl save];
    PFRelation *relation = [item relationForKey:@"owners"];
    [relation addObject:girl];
    [item saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        //Do something after the last save...
    }];
});
Ryan Kreager
  • 3,571
  • 1
  • 20
  • 35
  • just tried this, see edited code above. still exactly the same error. grrrr. It's driving me mad. – Kex Dec 20 '14 at 11:53
  • I'm going to try this myself exactly as you wrote it and get it working. Might need to save in nested blocks to ensure a save prior to setting and saving the PFRelation. I'll keep you posted. – Ryan Kreager Dec 20 '14 at 13:39
  • Updated answer above - give that a try. – Ryan Kreager Dec 20 '14 at 14:57
  • Thank you so much. Totally understand now. The girl object has to finish saving before we query it again, therefore we create the relation in a completion block not outside in the main thread. Added my code above. Pretty similar to yours. Thanks again for the help. Really appreciate it. – Kex Dec 21 '14 at 06:50