我目前正在尝试将从网络下载的图像存储到 NSManagedObject 类中,这样我就不必在每次打开应用程序时都重新下载它。我目前有这两个课程。
植物.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 返回的数据也不为零。我的 managedObjectContext 也不为零。根据我的调试器,请求是在主线程上完成的。还有什么我应该检查的吗?!
此外,如果我退出视图并返回,图像将不会再次下载,并且会出现“已经”日志。但是,如果我关闭并重新打开应用程序,则必须重新下载它们,这很奇怪,因为其余的 CoreData 仍然存在。
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
更新#2
看来我所有的 ManagedObjectContext 都是一样的。它可能与缓存有关吗?