我已经为此苦苦挣扎了一段时间,Apple 的文档和 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];
});
}
}];
}
});
}