我正在尝试在网络请求完成后将数据保存到核心数据中。
在 AppDelegate
中,我有我的上下文。在下面的代码中获取上下文:
- (NSManagedObjectContext *)contex {
@synchronized(self) {
if (_contex == nil) {
_contex = [[NSManagedObjectContext alloc] init];
[_contex setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
return _contex;
}
}
正如 Apple 指南所说,我有一个与多个上下文共享的持久存储坐标。
这是我从网络获取数据、获取上下文并调用将新值保存到核心数据的方法的代码。
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localFile, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIImage *image;
if (!error) {
NSData *imageData = [NSData dataWithContentsOfURL:localFile];
image = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"thumbnailIsSetted" object:self userInfo:@{@"image": image,
@"PhotoUrl": photo.url}];
@synchronized(self) {
NSManagedObjectContext *context = [(SocialMapAppDelegate *)[[UIApplication sharedApplication] delegate] contex];
[Photo addThumbnailData:imageData toPicture:photo.url fromContext:context];
}
});
} else {
//if we get an error, we send the default icon
image = [UIImage imageNamed:@"Photo-thumbnail"];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"thumbnailIsSetted" object:self userInfo:@{@"cached image": image,
@"PhotoUrl": photo.url}];
});
}
}];
[task resume]; //we resume the task in case it is souspended
}];
这是我将数据保存到核心数据中的方法:
+ (void)addThumbnailData:(NSData *)data toPicture:(NSString *)pictureUrl fromContext:(NSManagedObjectContext *)context
{
if (pictureUrl && context) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
request.predicate = [NSPredicate predicateWithFormat:@"url == %@",pictureUrl];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if ([matches count] == 1) {
Photo *photo = [matches lastObject];
photo.thumbnailData = data;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
}
}
我不知道问题出在哪里,上下文不是 nil,而且我没有收到任何错误。如果我重新启动应用程序,数据就在那里。
最佳答案
我不建议使用多个上下文,除非您在应用程序中使用多线程设计。我建议将应用程序剥离到一个上下文,以避免必须传递通知。 99% 的时间根本不需要它。
此外,如果您使用父/子上下文,我不建议重复使用子上下文。它们应该是短暂的;用于单个任务,然后丢弃。原因是数据更改仅以一种方式流动;向上。如果你改变一个 child 的某些事情,它不会被推到任何 sibling 身上。此外,子上下文会过时。如果您在主要上下文中进行更改,所有子级都将过时。
您的 UI 应在整个应用程序中使用单个 NSManagedObjectContext
。这很可能会解决您的问题。
关于ios - 在应用程序关闭之前,Core Data 不会保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20735057/