I have a UITableView in an iOS project. When the user selects an item from the table, the object is retrieved from CoreData and stored in a “Player” object. This player object is then passed into another view controller.
My question is: If i make changes to attributes in this Player object, how do i then save those changes. How does CoreData know which Player object changed? I have not set up a playerID attribute as all the Core Data documentation says that it manages its own IDs and references.
MORE:
So, at the moment, im doing this (excuse the pseudo-code, i dont have my source code to hand right now):
Player *player1 = [NSFetchResultController objectAtIndex:0]
Player *player2 = [NSFetchResultController objectAtIndex:1]
GameViewController *gameVC = [[GameViewController alloc] init]
gameVC.player1 = player1;
gameVC.player2 = player2;
gameVC.managedObjectContext = self.managedObjectContext
[self performSegueWithIdentifier:@"Game"]
I am passing in objects of type Player to gameVC, which have no identifier (as Core Data doesnt need explicit ID attributes creating – allegedly!)
So how does the MOC in gameVC know exactly which objects to commit any changes to???
Changes you make to the Player object apply the the managed object context where the player was fetched into. If you pass your managed object context reference to the new view controller as well, then you can save the managed object context and the changes will be saved.
Along with all the other changes in that managed object context, so be careful about the changes that are in there.
To answer your edited question; when you save an moc you aren’t saving particular objects, you are saving all the changes in the manage object context. So it doesn’t need to know which objects to save.
To add some more explanation: a Managed Object Context is a sort of scratch pad. You pull objects out of a persistent store into the context and you can make changes to it. But those changes are not persistent until they are saved back to the persistent store. If you want to be more granular about your saving, you can create another managed object context with just the objects that you want to change. saving this context only saves those objects. However, changes to objects will not show up in other managed object contexts until you save them back into the persistent store.