在后台线程上下载图像时锁定核心数据

时间:2013-06-04 17:30:44

标签: ios multithreading core-data uiimage nsurlconnection

我尝试异步下载图像并将其存储在Core Data中。第一步是下载一个json文件,解析它,并在Feed数据库中为每个对象保存一个实体。那部分工作正常。

假设我最终在Core Data中使用了10个Bird对象。每只Bird都有一个名称,描述等,以及与BirdImage的多对多关系,BirdImage是它自己的实体。 BirdImage有一个" image_url"属性(字符串)和"图像"属性(可转换)。

现在,当我到应用程序中显示鸟类图片的屏幕时,我首先检查"图像" BirdImage的属性。如果它不为null,我只需设置whateverBirdEntity.image作为UIImageView的图像。如果它为null,我需要下载图像。代码如下:

@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上下文保存?

2 个答案:

答案 0 :(得分:1)

首先,我不确定您的图像是在单独的线程上下载的

 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];

  });

dispatch_get_main_queue()返回与主线程关联的主队列,因此您的[NSRunLoop currentRunLoop]将返回主线程运行循环,这不是很好的。

其次,将数据库中的图像保存为blob并不是一个好主意,因为数据库大小会急剧增加,而您的查询和其他操作将需要更长的时间来执行,因此您应该将它们保存在本地(文档目录) )或缓存它们一段时间,并在数据库中仅保存图像的路径。

第三,self.imageEntity = birdImage这不安全,可能会多次调用此行并且只下载一个图像,因此您丢失了对实体的引用,我认为这是图像的主要原因没有完全下载。

第四,您应该依赖使用AFNetworkingAFImageRequestOperation这将处理异步下载,您可以通过将图片网址与实体网址进行比较来保存图片。

答案 1 :(得分:0)

NSManagedObjectContext有一个名为performBlock:(或performBlockAndWait:)的方法,毫不奇怪,它会占用一个块。然后保证该块在上下文的线程上执行。您可以将connectionDidFinishLoading:中的代码放入传递给performBlock:的块中,从而有利于您:

void (^contextBlock)() = ... // your code here

[self.objectContext performBlock:contextBlock];

如果您需要在其他线程上进行UI更新或执行代码,您也可以在该块中使用dispatch_async