如何使用临时对象CoreData?

nul*_*ion 0 cocoa-touch core-data magicalrecord

我使用lib MagicalRecord(https://github.com/magicalpanda/MagicalRecord)进行CoreData.framework.

我不明白如何使用临时对象.

如何为临时对象创建NSManagedContext以及在关闭控制器后是否删除每个NSManagedObject?

Mar*_*les 5

在上下文中创建的所有对象都是临时对象,在保存该上下文时它们将成为永久对象.所以要丢弃它们,你只是不保存那个上下文.

假设您使用Apple的核心数据堆栈,创建一个新的(临时)上下文:

NSManagedObjectContext *tempChildContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
tempChildContext.parentContext = self.appDelegate.managedObjectContext;
Run Code Online (Sandbox Code Playgroud)

要保存更改,您需要执行两次保存,一次在临时上下文中,然后将其推送到主上下文中.

[tempChildContext performBlock:^{
   // do something that takes some time asynchronously using the temp context

   // push to parent
   NSError *error;
   if (![tempChildContext save:&error])
   {
      // handle error
   }

   // save parent to disk asynchronously
   [self.appDelegate.managedObjectContext performBlock:^{
      NSError *error;
      if (![self.appDelegate.managedObjectContext save:&error])
      {
         // handle error
      }
   }];
}];
Run Code Online (Sandbox Code Playgroud)

对不起,我不记得怎么用MagicalRecord来做,但MR只是CoreData的包装,所以它会起作用.我在第一个CoreData项目上停止使用MR.我建议你读一下:多上下文CoreData.