【问题标题】:How to work with temporary objects CoreData?如何使用临时对象 CoreData?
【发布时间】:2014-05-24 06:49:26
【问题描述】:

我将 lib MagicalRecord (https://github.com/magicalpanda/MagicalRecord) 用于 CoreData.framework。

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

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

【问题讨论】:

    标签: cocoa-touch core-data magicalrecord


    【解决方案1】:

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

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

    NSManagedObjectContext *tempChildContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    tempChildContext.parentContext = self.appDelegate.managedObjectContext;
    

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

    [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
          }
       }];
    }];
    

    对不起,我不记得如何使用 MagicalRecord 来实现,但 MR 只是 CoreData 的包装器,所以它可以工作。我停止在我的第一个 CoreData 项目中使用 MR。我建议您阅读以下内容:Multi-Context CoreData

    【讨论】:

      猜你喜欢
      • 2011-03-08
      • 2012-12-09
      • 1970-01-01
      • 2018-04-20
      • 2018-03-05
      • 2013-11-29
      • 2023-03-22
      • 2011-01-19
      • 1970-01-01
      相关资源
      最近更新 更多