我目前正在尝试将我从网站上下载的图像存储到NSManagedObject类中,因此我无需每次打开应用程序时都需要重新下载。我目前有这两个班。CoreData中的NSData没有正确保存
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 ...抱歉,如果很容易!]
谢谢!
编辑&更新:
图像下载是不是nil,似乎只是罚款就被下载后。它看起来像UIImageJPEGRepresentation返回的数据也不是零。我的managedObjectContext也不是零。根据我的调试器,请求在主线程上完成。还有什么我应该检查?!
此外,如果我退出视图并返回,将不会再次下载图像并且将出现“已准备好”日志。但是,如果我关闭并重新打开应用程序,则必须重新下载它们,这很奇怪,因为CoreData的其余部分仍然存在。
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
更新#2
看来,我所有的ManagedObjectContext是相同的。它可能与缓存有关吗?
你能提供更多的信息吗? 下载的图像不是零?完成块是在后台线程还是在主线程中处理? _managedObjectContext不是肯定的?并注意UIImageJPEGRepresentation()可能会返回零... – Alexander
请参阅编辑!谢谢:) – abisson
嗯,你是否在fetchedResultsController中使用相同的managedObjectContext?我在问,因为您正在使用_moc访问它,但通过self.moc创建resultsController? – Alexander