Magical Record - 在主线程块中获取ui,在后台返回nil [英] Magical Record - fetch in main thread block ui, in background return nil

查看:224
本文介绍了Magical Record - 在主线程块中获取ui,在后台返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Magical Record的新手,但是已经在stackoverflow上看到了几个问题,并且找不到我的问题的答案。

I'm new to Magical Record, but already have seen a few questions on stackoverflow, and can't find an answer to my question.

使用这种类型的构造找到具有谓词的项:

I have to find items with the predicate using this type of construction:

NSArray *result = [MOSomeItems MR_findAllWithPredicate:predicate];

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

On the main thread result returns some value, but the UI is freezing.

使用此构造时,结果返回nil值:

When using this construction, result returns nil value:

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

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

What is the best practice for fetching data in background?

推荐答案

您需要使用具有专用队列的上下文,然后使用提取的ID 。

You need to use a context with a private queue, and then pull the results out from the main context using the fetched IDs.

// 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数组中作为参数,但是这种方式更短。我还建议您查看创建获取请求(MagicalRecord有一个MR_fetchAllWithPredicate:方法),设置批量大小,并手动执行提取。这将允许Core Data以块为单位拉取您的数据,所有这些都在返回数组的场景之后,以防止阻塞您的线程。

You can also pull objects out using the -[NSManagedObjectContext objectWithID:] method, passing each of the objects in the privateObjectIDs array as the argument, but this way is shorter. I also suggest you look into creating a fetch request (MagicalRecord has a MR_fetchAllWithPredicate: method), setting a batch size, and executing the fetch manually. This will allow Core Data to pull your data in chunks, all behind the scenes of the returned array, to prevent blocking of your thread.

希望有帮助!

这篇关于Magical Record - 在主线程块中获取ui,在后台返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆