Magical Record save in background

有些话、适合烂在心里 提交于 2019-12-10 13:25:08

问题


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:

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!


回答1:


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:

[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).




回答2:


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.




回答3:


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.

http://pthiaga.blogspot.in/2014/11/running-database-fetch-core-data-in.html



来源:https://stackoverflow.com/questions/14459321/magical-record-save-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!