Core Data中的NSData未正确保存

时间:2012-11-29 17:02:59

标签: ios core-data ios6 nsfetchedresultscontroller

我目前正在尝试将我从网上下载的图像存储到NSManagedObject类中,这样我每次打开应用程序时都不必重新下载。我目前有这两个班。

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本身永远不会保存。我总是要REDOWNLOAD图像!有任何想法吗!? [非常新的CoreData ...对不起,如果这很容易!]

谢谢!

编辑&更新

图像下载不是零,在下载后显得很好。看起来UIImageJPEGRepresentation返回的数据也不是零。我的managedObjectContext也不是零。根据我的调试器,请求在主线程上完成。还有什么我应该检查的吗?!

此外,如果我退出视图并返回,则图像将不会再次下载,并且将显示“已经”日志。但是,如果我关闭并重新打开应用程序,它们将不得不重新加载,这很奇怪,因为CoreData的其余部分仍然存在。

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];

更新#2

看来我的所有ManagedObjectContext都是一样的。它可能与缓存有关吗?

enter image description here

2 个答案:

答案 0 :(得分:0)

首先要检查的是,获取后plantplant.picture是否为零?其次,您说请求是在主线程上进行的,并且您的上下文不是nil。但是,响应(在块内)是在主线程上吗?从您分享的代码我会说plant.picture是零,但其他事情也是可能的。

答案 1 :(得分:-2)

您需要确保pictureData的类型transformable 在您的课程中,您需要pictureData才能成为NSData

喜欢这个

@property (nonatomic, retain) id pictureData;