How do I create many temporary objects and then save only one using Core Data?

后端 未结 3 1331
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 02:20

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 requi

相关标签:
3条回答
  • 2021-02-14 02:49

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

    0 讨论(0)
  • 2021-02-14 02:56

    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.

    0 讨论(0)
  • 2021-02-14 02:58

    I prefer to use a NIL context and have a base domain model class to handle recursively adding objects to a valid context when I want to persist them. It works really nicely (and cleanly!)... code available here... Temporary Core Data

    0 讨论(0)
提交回复
热议问题