我刚刚读了MagicalRecord的博客文章的作者为什么contextForCurrentThread在MagicalRecord中不起作用。
contextForCurrentThread
已弃用,应改用saveWithBlock
,因为它为相关线程创建了一个安全的新NSManagedObjectContext
。
到目前为止,我一直在我的应用程序中广泛使用contextForCurrentThread
。但是,我无法弄清楚如何使用saveWithBlock
,因为我的获取和保存不一定是按顺序进行的。
目前我正在做这样的事情:
localContext = NSManagedObjectContext.MR_contextForCurrentThread
person = Person.MR_createInContext(localContext)
person.name = "John Smith"
The user may then browse around the app, different controllers, views etc. are displayed. Other objects may be created using a similar method to the code above.
Then at some arbitrary point in the future, when the user decides to save, I run this method:
localContext = NSManagedObjectContext.MR_contextForCurrentThread
localContext.MR_saveToPersistentStoreWithCompletion(
lambda { |success, error|
# ...
}
)
创建和更新对象然后在不使用contextForCurrentThread
的情况下保存它们的推荐方法是什么?
以下是新API的教程:http://ablfx.com/blog/article/2这是重新围栏: http://cocoadocs.org/docsets/MagicalRecord/2.1/
-
初始化
[MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];
-
交易洛克
[MagicalRecord cleanUp];
-
插入
Person *alex = [Person MR_createEntity]; alex.name = @"Alex"; alex.age = @23;
-
选择
/检索 aNSManagedObject 子类的全部内容
NSArray *people = [Person MR_findAll];
检索第一条记录
Person *aPerson = [Person MR_findFirst];
有条件地检索记录并排序
NSArray *people = [Person MR_findByAttribute:@"name" withValue:@"alex" andOrderBy:@"age" ascending:YES];
-
更新
更新检索到的实体就像操作其属性一样简单
aPerson.age = @56;
-
删除
删除所有记录
[Person MR_truncateAll];
检索单条记录后删除
[alex MR_deleteEntity];
-
救
对于要在磁盘上实际保存/更新/删除的任何实体调用以下方法
[[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
再次检查 MagicalRecord 存储库以获取更多保存选项
因此,我使用目标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
}];
- 创建一个独立的或嵌套的上下文,并在某个地方(AppDelegate、单一实例对象等(保留对它的引用
- 使用
performBlock:
和performBlockAndWait:
进行插入,读取,更新和删除 使用以下方法保存上下文:
[context performBlock:^{ ZAssert([context save:&error], @"Save failed: %@n%@", [error localizedDescription], [error userInfo]); }];
这似乎是解决此类问题的标准方法。它在网上得到了很好的描述,例如常见后台实践 - 后台核心数据。