开发者

NSFetchedResultsController performFetch on background thread

开发者 https://www.devze.com 2023-03-25 14:04 出处:网络
I have to perform a fetch via NSFetchedResultsController on a background thread. My current solution is structured like that:

I have to perform a fetch via NSFetchedResultsController on a background thread.

My current solution is structured like that:

dispatch_queue_t fetchQueue = dispatch_queue_create("backgroundfetching", NULL);

dispatch_async(fetchQueue,^{
    // 1. Create NSMana开发者_如何转开发gedObjectContext
    // 2. Create NSFetchRequest
    // 3. Create NSFetchedResultsController
    // 4. PerformFetch

    dispatch_async(dispatch_get_main_queue(),^{
        [[self table] reloadData];
    });
});

dispatch_release(fetchQueue);

My first tests ran well but is that the appropriate way?


Since the fetched results controller is intended to control the data that defines a tableview, it belongs on the foreground thread/operation that the UI runs on. It's rather pointless to put it on a background thread as you would lose all the advantages of using it in the first place.

I would also be concerned about the effects of sending the FRC delegate messages across asynchronous threads. I'm not sure how reliable that would be.

Having said all that, the sketch of your implementation looks fine as far as it goes.


I believe there is something fundamentally wrong with this approach, as you're sharing managed objects across threads (you're fetching objects on one thread and referencing them on your main thread). In practice it will work, but will sometimes lead to crashes. Because Apple makes it clear that the only ways to share managed objects across threads is using the objectWithID: method or the MOCDidSave notifications.

From the Core Data Programming Guide:

You fetch in one managed object context on a background thread, and pass the object IDs of the fetched objects to another thread. In the second thread (typically the application's main thread, so that you can then display the results), you use the second context to fault in objects with those object IDs (you use objectWithID: to instantiate the object).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号