【发布时间】:2016-10-14 23:53:06
【问题描述】:
根据苹果的指导方针,为了在主线程上使用托管对象,它们需要由仅限于主线程的上下文获取,好的,没关系。下面是我的代码...
AppDelegate *del = [[UIApplication sharedApplication] delegate];
dispatch_queue_t queue1 = dispatch_queue_create("com.MyApp.AppTask",NULL);
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_async(queue1, ^{
NSManagedObjectContext *workerContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
workerContext.persistentStoreCoordinator = del.persistentStoreCoordinator;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSArray *managedObject = [workerContext executeFetchRequest:fetchRequest error:nil];
dispatch_async(main, ^{
NSLog(@"%@",managedObject);
Person *objperson = [managedObject objectAtIndex:0];
objperson.firstname = @“test”;
BOOL s = [workerContext save:nil];
if (s) {
NSLog(@"done");
}
});
});
现在根据指南,我无法修改或保存由另一个线程创建的托管对象上下文。但上面的代码工作正常,修改和保存我的对象没有任何错误。因此,我可以修改由另一个线程获取的 MOC,甚至可以保存由另一个线程创建的 MOC。
请让我知道我这样做的方式是否错误,因为理想情况下我无法从主线程中保存后台线程的 MOC。
谢谢。
【问题讨论】:
标签: ios core-data grand-central-dispatch