Core Data background fetching via new NSPrivateQueueConcurrencyType

后端 未结 2 395
礼貌的吻别
礼貌的吻别 2021-01-29 19:19

Is it really so simple now in iOS5?

I used to perform a background fetch using this code in my AppDelegate:

dispatch_queue_t downloadQueue = dispatch_que         


        
相关标签:
2条回答
  • 2021-01-29 20:19

    Yes - it is really that easy now (in iOS 5.0). For iOS 4 compatibility, the previous hurdles remain, but the documentation is not too bad on thread confinement. Maybe you should add this to a wiki section?

    0 讨论(0)
  • 2021-01-29 20:25

    I'm trying to understand how this new API is implemented. My usual pattern for multithreaded core data is something like this:

    Usually in a NSOperation but simplified using dispatch_async in this example:

    dispatch_queue_t coredata_queue; // some static queue
    
    dispatch_async(coredata_queue, ^() {
        // get a new context for this thread, based on common persistent coordinator
        NSManagedObjectContext *context = [[MyModelSingleton model] threadedContext];
    
        // do something expensive
    
        NSError *error = nil;
        BOOL success = [context save:&error];
        if (!success) {
            // the usual.
        }
    
        // callback on mainthread using dispatch_get_main_queue();
    });
    

    Then the main thread will respond by updating the UI based on NSManagedObjectContextDidSaveNotification to merge the main context.

    The new API's seem to be a wrapper around this pattern, where the child context looks like it just takes the persistent coordinator from its parent to create a new context. And specifying NSPrivateQueueConcurrencyType on init will make sure the performBlock parameter is executed on the private queue.

    The new API doesn't seem to be much less code to type. Any advantages over the 'traditional' threading?

    0 讨论(0)
提交回复
热议问题