我已经为此苦苦挣扎了一段时间,苹果的文档和 SO 到目前为止没有帮助。我在 UIManagedDocument 上使用 ManagedObjectContext 并且下面的代码工作正常。然后我决定在 AppDelegate 中使用 Apple 的 CoreData 模板,因此在 AppDelegate 中创建模型、持久存储协调器和上下文。使用AppDelegate的上下文获取没有问题,但是后台保存是一个问题。我应该在我保存的线程上有本地上下文,并且按照Apple的说法,应该有相同的持久性存储协调器。但下面的代码实际上并没有保存数据。这里有人可以建议吗?谢谢。
- (void)fetchAndPersist
{
dispatch_queue_t ffetchQ = dispatch_queue_create("ForFetch", NULL);
dispatch_async(ffetchQ, ^{
NSManagedObjectContext *secureManagedObjectContext;
NSPersistentStoreCoordinator *coordinator = [appDelegate persistentStoreCoordinator];
if (coordinator != nil) {
secureManagedObjectContext = [[NSManagedObjectContext alloc] init];
[secureManagedObjectContext setPersistentStoreCoordinator:coordinator];
}
// find missing date
DataManager *dataManager = [[DataManager alloc] init];
NSDate *missingDate = [dataManager findMissingDateFromDate:selectedDate inContext:secureManagedObjectContext];
if (missingDate) {
// fetch and parse data
DataFetcher *dataFetcher = [[dataFetcher alloc] init];
NSDictionary *fetchResponse = [dataFetcher parseDataForDate:missingDate];
// persist it in a block and wait for it
[secureManagedObjectContext performBlock:^{
DataStore *dataStore = [[DataStore alloc] init];
BOOL parsingError = [dataStore persistData:fetchResponse inContext:secureManagedObjectContext];
if (parsingError) {
// handle error
} else {
dispatch_async(dispatch_get_main_queue(), ^{
// perform on main
[self fetchAndPersist];
});
}
}];
}
});
}
尝试使用父/子上下文:
http://www.cocoanetics.com/2012/07/multi-context-coredata/ http://www.cocoanetics.com/2012/07/multi-context-coredata/
在上面的链接中,您可以找到代码示例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)