开发者

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.


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜