ios – 如何使用Magical Record创建和更新对象并保存它们而不使用contextForCurrentThread

我刚刚读到MagicalRecord的博客文章的作者在 Why contextForCurrentThread Doesn’t work in MagicalRecord.

contextForCurrentThread已被弃用,saveWithBlock应该被替代使用,因为它为相关线程创建了一个安全的新NSManagedobjectContext.

到目前为止,我一直在使用contextForCurrentThread在我的应用程序.但是,我无法确定如何使用saveWithBlock,因为我的获取和保存不一定顺序发生.

目前我在做如下事情:

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

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

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

localContext = NSManagedobjectContext.MR_contextForCurrentThread
localContext.MR_savetoPersistentStoreWithCompletion(
  lambda { |success,error|
    # ...
  }
)

建议的方法是什么?更新对象,然后保存它们而不使用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
}];

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...