Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: Create multiple managed objects, but only save some?

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.

like image 604
Tesserex Avatar asked Aug 26 '10 15:08

Tesserex


People also ask

Can we have multiple managed object context in Core Data?

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.

Will you ever pass a managed object from one context to another context?

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.

How do I save an object in Core Data?

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 managed object context saves its changes where does it push changes next?

When one of the managed object contexts is saved, its changes are pushed through the persistent store coordinator to the persistent store.


1 Answers

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.

like image 125
Marcus S. Zarra Avatar answered Dec 27 '22 06:12

Marcus S. Zarra