I'm trying to write a favorites system for my app. I've already converted my model to a managed object. So imagine the user is presented a screen with a list of such objects. They can choose to save some to their favorites, which will persist them in core data.
The problem is, when I create all of these model objects, I do so with the managed object context. If the user saves a single one to their favorites, it's going to save the whole context, and persist every single entity. The extras won't be in their favorites, since adding to favorites constructs a "favorite" entity that gets saved and points to the object, which the others won't have. But all of the other objects will be saved needlessly.
What's the standard way out of this / standard way to design an iPhone favorites system? Should I separate my model into two classes, the one I show the user, and then one that saves to the db? That way I could construct my models without putting them into the MOC. But that would be a duplicated class with all the same fields.
Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.
You cannot pass NSManagedObjects between multiple contexts, but you can pass NSManagedObjectIDs and use them to query the appropriate context for the object represented by that ID.
To save an object with Core Data, you can simply create a new instance of the NSManagedObject subclass and save the managed context. In the code above, we've created a new Person instance and saved it locally using Core Data.
When one of the managed object contexts is saved, its changes are pushed through the persistent store coordinator to the persistent store.
There is not really a standard way to do this because Core Data expects you to save the objects you create. However, if you create the objects with:
id object = [[NSManagedObject alloc] initWithEntityDescription:entity inManagedObjectContext:nil];
They won't have a context to save against. Then for the ones you need to save you can:
[[self managedObjectContext] insertObject:object];
Then call -save:
on the context and only those that have had their context set will save.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With