views:

237

answers:

2

I am working on an application that will perform a search against an online service and generate many Result objects. A Result object is an NSManagedObject, initialized as required by associating it with an NSManagedObjectContext.

Users should be able to select a "Result" and save it as a "Favorite". In the application this is as simple as associating the Result entity with a new Favorite entity and saving the context.

The problem is that every single Result in the context of course gets saved to the database along with the one I want Favorited.

I've seen many examples of using multiple NSManagedObjectContext instances to manage various creation and persistence situations. All of them seem to revolve around the idea of creating new instances with one Context and then merging them on save into another context for the sake of avoiding another FetchRequest execution. These examples don't solve the problem as they still lead to every Result entity being saved.

Anyone have any suggestions? I'm totally tapped out on this.

+3  A: 

Create Result objects that are not NSManagedObject subclasses. When the user picks one, create a single managed instance and save that.

Steve Weller
I was simplifying the problem for the sake of brevity. The Result object is an entity with many properties and several relationships.The thought of duplicating the classes makes me throw up in my mouth :)
+3  A: 

You should use a different context for each object. Using a separate managed object context allows you to work as follows. When the user selects its favorite object, you just discard the contexts related to the remaining result objects. No need to merge changes etc. There is basically a tradeoff. You end up managing (creating/discarding) several contexts, but then you accomplish your goal easily. Otherwise, you can still do this using just a single context. However, you have to explicitly insert or delete each object as shown in the following code snippets.

Try this. Only for the favorite object you want to save, do the following:

[managedObjectContext insertObject:theFavorite];

For each of the other result objects do this instead:

[managedObjectContext deleteObject:aResult];

then save as usual

NSError *error = nil
if (![managedObjectContext save:&error]) {
   // Handle error

}

This will save ONLY your selected, favorite object.

unforgiven
We went with the first part of your answer. We're using a Context per object graph and saving that as needed.