获取MagicalRecord NSManagedContext在后台线程中使用
问题描述:
我使用MagicalRecord 2.2并试图在后台线程上默认运行我的读取查询,但似乎文档已过时。具体来说,它说:获取MagicalRecord NSManagedContext在后台线程中使用
If you need to create a new managed object context for use in non-main threads,
use the following method:
NSManagedObjectContext *myNewContext = [NSManagedObjectContext MR_newContext];
然而,MR_newContext
方法缺失(猜这是不建议使用)。有一个[NSManagedObjectContext MR_context]
方法,但我不知道它返回什么情况。深入到代码中,它创建了一个新的并发类型NSPrivateQueueConcurrencyType
的上下文,所以我猜这就是我正在寻找的。
任何人都可以确认这一点吗?
答
我想你最好用+ (NSManagedObjectContext *) MR_contextForCurrentThread;
。它的实现似乎就好了你的目的:
+ (NSManagedObjectContext *) MR_contextForCurrentThread;
{
if ([NSThread isMainThread])
{
return [self MR_defaultContext];
}
else
{
NSMutableDictionary *threadDict = [[NSThread currentThread] threadDictionary];
NSManagedObjectContext *threadContext = [threadDict objectForKey:kMagicalRecordManagedObjectContextKey];
if (threadContext == nil)
{
threadContext = [self MR_contextWithParent:[NSManagedObjectContext MR_defaultContext]];
[threadDict setObject:threadContext forKey:kMagicalRecordManagedObjectContextKey];
}
return threadContext;
}
}
答
你可能想使用
[NSManagedObjectContext MR_confinementContext]
虽然,作为CoreData团队已经有效地弃用约束背景下,这个名字很可能也会改变。
请勿使用此方法。它随时会在你身上崩溃。 – casademora 2014-10-02 08:32:09
不建议在这里详细:http://saulmora.com/2013/09/15/why-contextforcurrentthread-doesn-t-work-in-magicalrecord/ – Ger 2014-10-02 17:34:18
@Ger,哇,谢谢,不知道。 – orkenstein 2014-10-02 17:43:08