Editing Core Data Relational Data
I have User and Friend entities in my data model, being a one User to many Friends relationship.
My ViewController, is instantiated with an instance variable for User (*user), and therefore I can access all friends by loading user.friends as friends is defined as an NSSet in my User object.
In my code I load all friends in an NSMutableArray, do some stuff, and potentially before leaving want to add additional friends, an开发者_如何转开发d edit the attributes of existing friends. I'm at a loss on how I can add/edit friends.
Should I edit the NSMutableArray of friend objects, and save that back to the User.context? If so, how?
If editing a friend, should I copy existing friend object, change values, delete old object from the array and add the new (copied and updated) one?
I hope this makes sense...
You can modify your Friend objects (no need to make new copies and delete old ones).
Try this:
// create a mutable copy of an array from the set of the user's friends
NSMutableArray *friends = [[user.friends allObjects] mutableCopy];
// modify friends array or any Friend objects in the array as desired
// create a new set from the array and store it as the user's new friends
user.friends = [NSSet setWithArray:friends];
[friends release];
// save any changes
NSManagedObjectContext *moc = [user managedObjectContext];
if ([moc hasChanges] && ![moc save:&error]) {
// handle error
}
You could also use a mutable set instead of an array:
// create a mutable copy of the set of the user's friends
NSMutableSet *friends = [user.friends mutableCopy];
// modify friends set or any Friend objects in the set as desired
// create a new set from the set and store it as the user's new friends
user.friends = [NSSet setWithSet:friends];
[friends release];
// save any changes
NSManagedObjectContext *moc = [user managedObjectContext];
if ([moc hasChanges] && ![moc save:&error]) {
// handle error
}
If you have a pointer/reference to a NSManagedObject you can edit all attributes. Say you get one friend like this:
Friend *aFriend = [user.friends anyObject];
[aFriend setLastName:@"new Lastname"];
NSError *error = nil;
[[self managedObjectContext] save:&error];
To add a friend do this:
Friend *aNewFriend = [NSEntityDescription insertNewObjectForEntityForName:@"friend" inManagedObjectContext:[self managedObjectContext]];
[user addFriendsObject:aNewFriend];
NSError *error = nil;
[[self managedObjectContext] save:&error];
However this will not add the new friend to the NSMutableArray that you created from the user.friends set earlier.
精彩评论