后台线程中的Coredata CRUD操作?

Coredata CRUD operations in background thread?

我在我的应用程序

Create/Update NSManagedObject 中使用来自苹果的以下代码片段
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
    //
    //

NSManagedObjectContext *private = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [private setParentContext:mainMoc];

        [private performBlock:^{
            for (NSDictionary *jsonObject in jsonArray) {
                NSManagedObject *mo = …; //Managed object that matches the incoming JSON structure
                //update MO with data from the dictionary
            }
            NSError *error = nil;
            if (![private save:&error]) {
                NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
                abort();
            }
            [mainMoc performBlockAndWait:^{
                NSError *error = nil;
                if (![mainMoc save:&error]) {
                    NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
                    abort();
                }
            }];
        }];




    dispatch_async( dispatch_get_main_queue(), ^{
        // Add code here to update the UI/send notifications based on the
        // results of the background processing
    });
});

我有两个疑惑

  1. 为了使用上面的代码从我的模型中读取值,

    [private performBlock:^{}); 是必需的吗?

  2. 后台线程中的Create/Update操作是否有更好的方法。我是否使用了上述操作的最佳方法?

提前致谢

来自苹果文档Concurrency

performBlock: and performBlockAndWait: ensure the block operations are executed on the queue specified for the context. The performBlock: method returns immediately and the context executes the block methods on its own thread. With the performBlockAndWait: method, the context still executes the block methods on its own thread, but the method doesn’t return until the block is executed.

当您使用 NSPrivateQueueConcurrencyType 时,上下文创建并管理一个私有队列。

因此,如果您使用 performBlock:,则无需创建另一个调度队列,因为它是在块内异步执行操作。否则,如果你使用 performBlockAndWait: 等待直到完成它的操作执行,在这种情况下你应该使用另一个调度队列。

因此,最佳做法是避免使用另一个调度队列。例如

NSManagedObjectContext *private = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
[private setParentContext:mainMoc];

[private performBlock:^{
    for (NSDictionary *jsonObject in jsonArray) {
        NSManagedObject *mo = …; //Managed object that matches the incoming JSON structure
        //update MO with data from the dictionary
    }
    NSError *error = nil;
    if (![private save:&error]) {
        NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
        abort();
    }
    [mainMoc performBlockAndWait:^{
        NSError *error = nil;
        if (![mainMoc save:&error]) {
            NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
            abort();
        }
    }];
}];