魔法logging – 取主线程块ui,在后台返回nil

我是新来的魔法logging,但已经看到了一些问题上的计算器,并找不到我的问题的答案。

我必须使用这种types的构造来查找具有谓词的项目:

NSArray *result = [MOSomeItems MR_findAllWithPredicate:predicate]; 

在主线程结果返回一些值,但UI是冻结。

当使用这个构造时,结果返回零值:

 dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ NSArray *result = [MOSomeItems MR_findAllWithPredicate:predicate]; }); 

在后台获取数据的最佳做法是什么?

您需要使用带有专用队列的上下文,然后使用提取的ID从主上下文中提取结果。

 // Create a child context of our main context NSManagedObjectContext *privateContext = [NSManagedObjectContext MR_context]; // When using private contexts you must execute the core data code in it's private queue using performBlock: or performBlockAndWait: [privateContext performBlock:^{ // Execute your fetch NSArray *privateObjects = [MOSomeItems MR_findAllWithPredicate:predicate inContext:privateContext]; // Convert your fetched objects into object IDs which can be pulled out of the main context NSArray *privateObjectIDs = [privateObjects valueForKey:@"objectID"]; // Return to our main thread dispatch_async(dispatch_get_main_queue(), ^{ // Create a new predicate to use to pull our objects out NSPredicate *mainPredicate = [NSPredicate predicateWithFormat:@"self IN %@", privateObjectIDs]; // Execute your fetch NSArray *finalResults = [MOSomeItems MR_findAllWithPredicate:mainPredicate]; // Now you can use finalResults however you need from the main thread }); }]; 

您也可以使用 – [NSManagedObjectContext objectWithID:]方法将对象拉出,将privateObjectIDs数组中的每个对象作为parameter passing,但这种方法更短。 我也build议你看看创build一个获取请求(MagicalRecord有一个MR_fetchAllWithPredicate:方法),设置批量大小,并手动执行提取。 这将允许核心数据以块的forms提取数据,所有数据都在返回数组的背后,以防止阻塞你的线程。

希望有所帮助!