xcode 神奇的记录在后台保存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14459321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Magical Record save in background
提问by Linus
I'm using the Magical Record framework to save user settings. Now, for the first time, I want to save things in a background thread. On Magical Record's github page is an example snippet I don't fully understand:
我正在使用 Magical Record 框架来保存用户设置。现在,我第一次想在后台线程中保存内容。在 Magical Record 的 github 页面上有一个我不完全理解的示例片段:
Person *person = ...;
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
Person *localPerson = [person MR_inContext:localContext];
localPerson.firstName = @"John";
localPerson.lastName = @"Appleseed";
}];
Why is the first line needed? Can't I just completely create the Person in the block? Thank you!
为什么需要第一行?我不能在块中完全创建 Person 吗?谢谢!
回答by Alladinian
Of course you can. This example just grabs a person
object from the outer context (your default one or whatever) and gives you a pointer to it in the localContext
so you can update it in the background. If you were to create a person
from scratch you could do something like this:
当然可以。这个示例只是person
从外部上下文(您的默认上下文或其他上下文)中获取一个对象,并在 中为您提供一个指向它的指针,localContext
以便您可以在后台更新它。如果您要person
从头开始创建一个,您可以执行以下操作:
[MagicalRecord saveInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
Person *localPerson = [Person MR_createInContext:localContext];
localPerson.firstName = @"John";
localPerson.lastName = @"Appleseed";
}];
And you're done.
你已经完成了。
PS. Note that MR_createInContext:
is a class method called on Person
class (instead of MR_inContext:
instance method which is called on person
instance).
附注。请注意,这MR_createInContext:
是在类上调用的类方法Person
(而不是在MR_inContext:
实例上调用的实例方法person
)。
回答by Stephan Michels
Yes, you can create the Person also in the block. The inContext: method is only necessary if you fetch for example a Person from a different context. Beware, if you create the Person in the block, then you should use the createInContext: method.
是的,您也可以在块中创建 Person。仅当您从不同的上下文中获取例如 Person 时,才需要 inContext: 方法。请注意,如果您在块中创建 Person,那么您应该使用 createInContext: 方法。
回答by Priya Thiagarajan
Magical Record save and fetch are Context-Based. So, You can either create a record in the default context or create record in a new context using MR_createInContext method. But, while fetching the records, the context should be the same as you created.
Magical Record 保存和获取是基于上下文的。因此,您可以使用 MR_createInContext 方法在默认上下文中创建记录或在新上下文中创建记录。但是,在获取记录时,上下文应该与您创建的相同。
http://pthiaga.blogspot.in/2014/11/running-database-fetch-core-data-in.html
http://pthiaga.blogspot.in/2014/11/running-database-fetch-core-data-in.html