What is the replacement method for this MagicalRecord deprecated call?

会有一股神秘感。 提交于 2019-11-26 09:56:43

问题


How do I find the replacement method in MagicalRecord for this (which has been deprecated)? I have looked at Google, SO and the docs; nothing seems to be a replacement, and of course, nothing in the docs tell you what replaced the deprecated method. :-{

[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveErrorHandler:^(NSError *error)

回答1:


The deprecated method in question is:

[NSManagedObjectContext MR_contextForCurrentThread]

I did write a little blog post about this a while ago, though I admit it is on my personal blog, and not in any official docs. But, TL;DR, the bottom line is, in the world of GCD and queues, you cannot guarantee a 1-1 mapping of a queue to a thread, despite GCD being run on threads. The way to make sure things work going forward for you is using the following pattern:

[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
    //make your changes in the localContext
}];

This solves the subtle cross thread issues that crop up in contextForCurrentThread by simply enforcing the rule that you should do all work in a different thread in a thread specific context. By creating a new context every time you save, and not re-using the context, you will guarantee to not cross threads, and to not crash your app 1% of the time.




回答2:


casademora is correct but I'll try to be more precise because I encounter some issues when converting my

    [[NSManagedObjectContext MR_contextForCurrentThread] MR_saveToPersistentStoreWithCompletion:nil];

into

    [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext)

You have to be careful to change or create your entities inside the block but it's not enough.

To retrieve your entities you must use selection request with context too.

MR_findFirstByAttribute:withValue

is not enough and updates won't be saved. You have to use instead

MR_findFirstByAttribute:withValue:InContext:localContext

And when creating entity, it's the same

MR_createEntity

must be change to

MR_createEntityInContext:localContext

Then it works like a charm :)



来源:https://stackoverflow.com/questions/20535419/what-is-the-replacement-method-for-this-magicalrecord-deprecated-call

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