【发布时间】:2012-11-29 17:02:59
【问题描述】:
我目前正在尝试将从网络下载的图像存储到 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 都是一样的。会不会跟缓存有关?
【问题讨论】:
-
您能提供更多信息吗?下载的图像不是零?完成块是在后台线程还是在主线程中处理? _managedObjectContext 肯定不是 nil 吗?小心 UIImageJPEGRepresentation() 可能会返回 nil...
-
嗯,您在 fetchedResultsController 中使用相同的 managedObjectContext 吗?我问是因为您使用 _moc 访问它一次,但在通过 self.moc 创建 resultsController 时?
-
它们看起来是一样的......但仍然无法正常工作。请参阅更新 #2。
-
这是您在应用中使用的唯一 MOC 吗?因为如果它例如是您的主要上下文的子上下文,那么您可能忘记合并并保存父上下文?!
-
只有它一个。该死的..到底是什么:S。现在..我刚刚尝试了一个简单的用户对象。我得到了对象,更改了名字,保存了它,关闭了应用程序并重新打开了它。不过,这个名字并没有改变。我第一次创建数据是通过 RestKit ......但后来我似乎无法更改数据:S
标签: ios core-data ios6 nsfetchedresultscontroller