現在、アプリケーションを開くたびに再ダウンロードする必要がないように、Web からダウンロードした画像を NSManagedObject クラスに保存しようとしています。私は現在、この2つのクラスを持っています。
Plant.h
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) PlantPicture *picture;
PlantPicture.h
@property (nonatomic, retain) NSString * bucketName;
@property (nonatomic, retain) NSString * creationDate;
@property (nonatomic, retain) NSData * pictureData;
@property (nonatomic, retain) NSString * slug;
@property (nonatomic, retain) NSString * urlWithBucket;
今、私は次のことを行います:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
PlantCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
Plant *plant = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.plantLabel.text = plant.name;
if(plant.picture.pictureData == nil)
{
NSLog(@"Downloading");
NSMutableString *pictureUrl = [[NSMutableString alloc]initWithString:amazonS3BaseURL];
[pictureUrl appendString:plant.picture.urlWithBucket];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:pictureUrl]];
AFImageRequestOperation *imageOperation = [AFImageRequestOperation imageRequestOperationWithRequest:request success:^(UIImage *image) {
cell.plantImageView.image = image;
plant.picture.pictureData = [[NSData alloc]initWithData:UIImageJPEGRepresentation(image, 1.0)];
NSError *error = nil;
if (![_managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}];
[imageOperation start];
}
else
{
NSLog(@"Already");
cell.plantImageView.image = [UIImage imageWithData:plant.picture.pictureData];
}
NSLog(@"%@", plant.name);
return cell;
}
画像オブジェクトだけでなく、植物情報も存在します。ただし、NSData 自体は、アプリケーションの開閉中に保存されることはありません。私はいつも画像を再ダウンロードする必要があります! 何か案は!?[CoreData を初めて使用します... 簡単でしたら申し訳ありません!]
ありがとう!
編集と更新:
画像のダウンロードはゼロではなく、ダウンロード後に問題なく表示されます。UIImageJPEGRepresentation によって返されるデータも nil ではないようです。私の managedObjectContext も nil ではありません。私のデバッガーによると、リクエストはメインスレッドで行われます。他に確認すべきことはありますか?!
また、ビューを終了して戻ってきた場合、画像は再度ダウンロードされず、「既に」ログが表示されます。ただし、アプリを閉じて再度開くと、再ダウンロードする必要があります。CoreData の残りの部分がまだ存在するため、これは奇妙です。
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
アップデート #2
私の ManagedObjectContext はすべて同じようです。キャッシュと関係があるのでしょうか?