views:

42

answers:

2

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.

+1  A: 

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:

[object setContext:[self managedObjectContext]];

Then call -save: on the context and only those that have had their context set will save.

Marcus S. Zarra
And this is safe? I saw that the convenience method for constructing NSMOs replaces a pretty large chunk of code.
Tesserex
Yes it is safe, what convenience method? The method I described is the same as calling `[NSEntityDescription insert...]`. The only difference is that the `NSEntityDescription` method returns an autoreleased object.
Marcus S. Zarra
Ok, you just have your second thing backward. The correct call is `[[self managedObjectContext] addObject:object]`, the converse that you have there doesn't exist.
Tesserex
Correct, coding from memory and without a compiler can produce such minor errors :)
Marcus S. Zarra
A: 

Wouldn't it be easier to have an isFavorite property on your managed objects. Then in your favorites view you can filter based on that?

Elfred
But that still doesn't get around the fact that I'm saving a whole lot of data that I don't need.
Tesserex