我正在尝试异步下载图像并将它们存储在核心数据中。第一步是下载一个 json 文件,对其进行解析,然后在 Core Data 中为提要中的每个对象保存一个实体。那部分工作正常。
假设我最终在 Core Data 中有 10 个 Bird 对象。每个 Bird 都有一个名称、描述等,并与 BirdImage 存在一对多关系,这是它自己的实体。BirdImage 有一个“image_url”属性(字符串)和一个“图像”属性(Transformable)。
现在,当我到达应用程序中将显示鸟类图片的屏幕时,我首先检查 BirdImage 的“图像”属性。如果它不为空,我只是将whateverBirdEntity.image 设置为UIImageView 的图像。如果为空,我需要下载图像。在这样的代码中:
@property (nonatomic, strong) AssetRequest *assetRequest; //this is just a wrapper for an asset url, cache policy, and time out
@property (nonatomic, strong) NSURLRequest *assetURLRequest;
@property (nonatomic, strong) NSURLConnection *assetConnection;
@property (nonatomic, strong) NSMutableData *assetConnectionData;
@property (nonatomic, strong) BirdImage *imageEntity;
@property (nonatomic, strong) NSManagedObjectContext *objectContext;
...
- (void)load {
dispatch_async(dispatchQueue, ^{
//Check for the image in Core Data
self.objectContext = [[NSManagedObjectContext alloc]
initWithConcurrencyType:NSPrivateQueueConcurrencyType];
self.objectContext.parentContext = [[CoreDataController sharedController] managedObjectContext];
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"BirdImage"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"image_url = %@", [self.assetRequest.assetURL absoluteString]];
[fetch setPredicate:predicate];
NSArray *objects = [self.objectContext executeFetchRequest:fetch error:nil];
if ([objects count] > 0)
{
BirdImage *birdImage = [objects objectAtIndex:0];
if (birdImage.image) {
dispatch_async(dispatch_get_main_queue(), ^{
BirdAsset *asset = [[BirdAsset alloc] init];
asset.url = [NSURL URLWithString:birdImage.image_url];
asset.image = birdImage.image;
if (self.successBlock)
self.successBlock(asset); //the caller will use asset.image for the UIImageView
});
return;
}else{
//no image found, need to download it
self.imageEntity = birdImage; //this is the entity I want to re-save in Core Data once the image finishes downloading
dispatch_async(dispatch_get_main_queue(), ^{
self.assetURLRequest = [NSURLRequest requestWithURL:self.assetRequest.assetURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:self.assetRequest.timeOut];
self.assetConnection = [[NSURLConnection alloc] initWithRequest:self.assetURLRequest delegate:self startImmediately:NO];
[self.assetConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[self.assetConnection start];
});
}
}
}];
});
}
然后,当下载完成时:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
dispatch_async(dispatchQueue, ^{
UIImage *resultImage = [UIImage decompressImageFromData:self.assetConnectionData];
NSData *resultData = UIImagePNGRepresentation(resultImage);
DLog(@"saving to core data: %@", self.imageEntity.image_url); //THIS HAPPENS 10 TIMES (every time)
self.imageEntity.image = resultImage;
@try {
NSError *saveError = nil;
if (![self.objectContext save:&saveError])
NSLog(@"saveError %@", saveError);
}
@catch (NSException *exception) {
NSLog(@"Exception: %@", exception);
}
[[CoreDataController sharedController] saveContext];
BirdAsset *finalAsset = [[BirdAsset alloc] init];
finalAsset.data = resultData;
finalAsset.image = resultImage;
finalAsset.url = [NSURL URLWithString:self.imageEntity.image_url];
DLog(@"SUCCESS"); //THIS HAPPENS anywhere from 4-7 times. I never get all 10 images.
dispatch_async(dispatch_get_main_queue(), ^{
if (self.successBlock)
self.successBlock(finalAsset);
});
});
}
图像下载正常,当我检查我的数据库时,我可以看到每个 BirdImage“图像”的 BLOB 数据。问题在于,在 10 张图像中,实际上显示了其中的随机数(第一次运行时显示 4-7 张)。然后,如果我再次返回此屏幕,应用程序将锁定,没有错误消息或崩溃。我怀疑这是某种核心数据锁定。
我知道我必须“从创建它的同一线程访问上下文”。但是如果我用不同的方法(比如上面的 load 和 connectionDidFinishLoading 方法)访问上下文,我怎么能使用同一个线程呢?换句话说,如何修改我的代码,以便在图像完成下载时执行线程安全的 CoreData 上下文保存?