NSData in CoreData is not saving properly
Posted
by
abisson
on Stack Overflow
See other posts from Stack Overflow
or by abisson
Published on 2012-11-29T17:02:59Z
Indexed on
2012/11/29
17:03 UTC
Read the original article
Hit count: 204
I am currently trying to store images I download from the web into an NSManagedObject class so that I don't have to redownload it every single time the application is opened. I currently have these two classes.
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;
Now I do the following:
- (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;
}
The plant information is present, as well as the picture object. However, the NSData itself is NEVER saved throughout the application opening and closing. I always have to REDOWNLOAD the image! Any ideas!? [Very new to CoreData... sorry if it is easy!]
thanks!
© Stack Overflow or respective owner