Parse - saving related objects

筅森魡賤 提交于 2020-02-03 05:34:09

问题


I'm using Parse for the back end in my project.

As you would imagine there are quite a few relations in the data model. A lot of the time I create a "parent" object and all of its "children" at the same moment and save them all to Parse.

Now, when doing this is it necessary to save the children individually? The same for files etc...

First example - Adding an avatar to a user object

UIImage *image = // image from camera
NSData *pngData = UIImagePNGRepresentation(image);
PFFile *imageFile = [PFFile fileWithData:pngData];
[[PFUser currentUser] setObject:imageFile forKey:"avatar"];

OK, so on the device I can reference the @"avatar" key on the user and get the avatar file. But how should this be saved to Parse?

If I do...

[[PFUser currentUser] saveInBackground];

Will this save the new file that was added? Or do I need to save the file first and wait for this to succeed before then adding it into the user object and then saving the user object?

Second example

Creating a tree of objects...

PFObject *family = [PFObject objectWithClassName:@"Family"];
[family setObject:@"Smith" forKey:@"familyName"];

PFObject *person1 = [PFObject objectWithClassName:@"Person"];
[person1 setObject:@"Bob" forKey:@"name"];

PFObject *person2 = [PFObject objectWithClassName:@"Person"];
[person2 setObject:@"Alice" forKey:@"name"];

PFObject *person3 = [PFObject objectWithClassName:@"Person"];
[person3 setObject:@"Chris" forKey:@"name"];

[family setObject:@[person1, person2, person3] forKey:@"members"];

How would I save this collection of objects?

Can I just do [family saveInBackground];?

Or do I have to go through a process of saving every Person object first and checking that it worked before saving the family object?


回答1:


As long as the relationship between parent and child is Pointer, you don't have to save the child first. PFRelation works differently, but a save on the parent object will also save children related as pointers. This is true for Cloud Code, and I am pretty sure it holds true for the device as well.

Some details in this answer: https://www.parse.com/questions/cloud-code-efficient-hierarchy-saving




回答2:


Yes that will do...in fact there is a wide range of methods for saving the contents

Saving an Object to Parse

– save
– save:
– saveInBackground
– saveInBackgroundWithBlock:
– saveInBackgroundWithTarget:selector:
– saveEventually
– saveEventually:
Saving Many Objects to Parse

+ saveAll:
+ saveAll:error:
+ saveAllInBackground:
+ saveAllInBackground:block:
+ saveAllInBackground:target:selector:

Refer Here for more



来源:https://stackoverflow.com/questions/23651516/parse-saving-related-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!