【发布时间】:2017-10-23 18:38:19
【问题描述】:
我在我的应用程序中使用来自苹果的以下代码 sn-ps 创建/更新 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
});
});
我有两个疑问
-
仅使用上面的代码从我的模型中读取值,
[private performBlock:^{});必填? - 对于后台线程中的创建/更新 操作是否有更好的方法。我是否使用了上述操作的最佳方法?
提前致谢
【问题讨论】:
标签: objective-c core-data nsmanagedobject nsmanagedobjectcontext