如何使用魔法logging来创build和更新对象,并保存它们而不使用contextForCurrentThread

我刚刚阅读MagicalRecord的博客文章的作者为什么contextForCurrentThread不能在MagicalRecord工作 。

不推荐使用saveWithBlock应使用saveWithBlock因为它为相关线程创build了一个安全的新NSManagedObjectContext

我一直在我的应用程序广泛使用contextForCurrentThread到目前为止。 然而,我很难找出如何使用saveWithBlock而我的提取和保存不一定顺序发生。

目前我正在做的事情如:

 localContext = NSManagedObjectContext.MR_contextForCurrentThread person = Person.MR_createInContext(localContext) person.name = "John Smith" 

用户然后可以浏览应用程序,不同的控制器,视图等。 其他对象可以使用与上述代码类似的方法来创build。

然后在将来的某个任意点,当用户决定保存时,我运行这个方法:

 localContext = NSManagedObjectContext.MR_contextForCurrentThread localContext.MR_saveToPersistentStoreWithCompletion( lambda { |success, error| # ... } ) 

推荐的方法是创build和更新对象,然后保存它们而不使用contextForCurrentThread

所以,我使用客观的C而不是RubyMotion,但你应该能够像这样的东西:

 MagicalRecord.saveWithBlock( lambda { |localContext| person = Person.MR_createInContext(localContext) #update person stuff here } ) 

编辑

如果以后要保存上下文,则只需要坚持:

 // Somewhere in your ViewController, etc NSManagedObjectContext *context = [NSManagedObjectContext MR_confinementContext]; // Somewhere else Person *p = [Person MR_createInContext:context]; // And in yet another method [context MR_saveToPersistentStoreAndWait]; 

这里的主要想法是,你只需要坚持上下文,并在你准备好的时候对它进行操作。 如果你想要保存一个背景,你可以使用下面的方法:

 [context MR_saveToPersistentStoreCompletion:^(BOOL success, NSError *error){ //called on the main thread when save is complete }]; 

这里是一个新的api的教程: http ://ablfx.com/blog/article/2这里是refence: http ://cocoadocs.org/docsets/MagicalRecord/2.1/

  1. 在里面

    [MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];

  2. 的dealloc

    [MagicalRecord cleanUp];

  3. Person *alex = [Person MR_createEntity]; alex.name = @"Alex"; alex.age = @23;

  4. select

    /全部检索aNSManagedObject子类NSArray *people = [Person MR_findAll];

    //检索第一个loggingPerson *aPerson = [Person MR_findFirst];

    NSArray *people = [Person MR_findByAttribute:@"name" withValue:@"alex" andOrderBy:@"age" ascending:YES];

  5. 更新

    //更新一个获取的实体就像操作它的属性一样简单aPerson.age = @56;

  6. 删除

    //删除所有logging[Person MR_truncateAll];

    //删除单个logging,找回后[alex MR_deleteEntity];

  7. 保存

    //对于任何实体在磁盘调用中实际被保存/更新/删除方法[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];

    / /再次检查MagicalRecord回购更多的保存选项

我可能在这里弄错了,但是我认为“魔法logging”并没有为这个用例做准备。 下面是我如何在纯数据中做你想做的事情:

  1. 创build一个独立的或嵌套的上下文,并保持某处(AppDelegate,单例对象等)对它的引用
  2. 使用performBlock:performBlockAndWait:执行插入,读取,更新和删除操作performBlockAndWait:
  3. 保存上下文:

     [context performBlock:^{ ZAssert([context save:&error], @"Save failed: %@\n%@", [error localizedDescription], [error userInfo]); }]; 

这似乎是解决这类问题的标准方法。 它在网上很好地被描述,例如通用背景实践 – 背景中的核心数据 。