Pau*_*ess 10 core-data ios magicalrecord rubymotion
我刚刚阅读了MagicalRecord关于为什么contextForCurrentThread在MagicalRecord中不起作用的博客文章的作者.
contextForCurrentThread不推荐使用,saveWithBlock应该使用它,因为它NSManagedObjectContext为相关的线程创建了一个安全的新东西.
contextForCurrentThread到目前为止,我一直在我的应用程序中广泛使用.但是,我无法确定如何使用,saveWithBlock因为我的提取和保存不一定按顺序发生.
目前我正在做的事情如下:
localContext = NSManagedObjectContext.MR_contextForCurrentThread
person = Person.MR_createInContext(localContext)
person.name = "John Smith"
然后,用户可以在app周围浏览,显示不同的控制器,视图等.可以使用与上面的代码类似的方法来创建其他对象.
然后在将来的某个任意点,当用户决定保存时,我运行这个方法:
localContext = NSManagedObjectContext.MR_contextForCurrentThread
localContext.MR_saveToPersistentStoreWithCompletion(
lambda { |success, error|
# ...
}
)Run Code Online (Sandbox Code Playgroud)
建议和更新对象然后在不使用的情况下保存它们的建议方法是什么contextForCurrentThread?
lbs*_*eek 18
这是一个新api的教程:http ://ablfx.com/blog/article/2这里是refence:http://cocoadocs.org/docsets/MagicalRecord/2.1/
在里面
[MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];
的dealloc
[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
}
)
Run Code Online (Sandbox Code Playgroud)
编辑
如果您想稍后保存上下文,您只需要坚持下去:
// 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];
Run Code Online (Sandbox Code Playgroud)
这里的主要想法是,您只需要保持上下文并在准备好时对其执行操作.如果要进行后台保存,可以使用以下方法:
[context MR_saveToPersistentStoreCompletion:^(BOOL success, NSError *error){
//called on the main thread when save is complete
}];
Run Code Online (Sandbox Code Playgroud)