我需要从后台线程更改一些实体,所以我执行以下操作:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSManagedObjectContext *parent = [Default managedObjectContext];
NSManagedObjectContext *editContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:parent.concurrencyType];
[editContext setPersistentStoreCoordinator:[Default persistentStoreCoordinator]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(saveChanges:)
name:NSManagedObjectContextDidSaveNotification
object:editContext];
NSFetchRequest *request = [NSFetchRequest new];
...
NSArray *fetchedObjects = [context executeFetchRequest:request error:nil];
NSError *error;
[editContext save:&error]
});
它正在工作,但有时它会停止工作,只是退出 executeFetchRequest:request 上的函数。它发生在模拟器上。那么从后台线程更改数据是正确的方法吗?