Saving array of images in core data as transformable

325 Views Asked by At

I want to add my imageArray into coredata as transformable but this is not storing properly.

My save button coding.

  - (IBAction)saveButton:(id)sender {

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"FoodInfo" inManagedObjectContext:context];
NSAttributeDescription *messageType = [[NSAttributeDescription alloc] init];
[messageType setName:@"photos"];
[messageType setAttributeType:NSTransformableAttributeType];
[imagesForShow addObject:messageType];
 NSError *error = nil;
if (![context save:&error]) {
    NSLog(@"Unable to save context for class" );
} else {
    NSLog(@"saved all records!");
    [context save:nil];
}
//[newEntry setValue:imagesForShow forKey:@"images"];


}
  • Here 'imagesForShow' is my array of images.

When iam going to fetch this image array , this showing nil

- (void)viewDidLoad {
[super viewDidLoad];

NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"FoodInfo"];
[request setReturnsObjectsAsFaults:NO];
arrayForPhotos = [[NSMutableArray alloc]initWithArray:[context executeFetchRequest:request error:nil]];




// Do any additional setup after loading the view.
}

What I am doing wrong with this code. Thanks.

1

There are 1 best solutions below

0
Tom Harrington On

In your save code:

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newEntry = [NSEntityDescription
     insertNewObjectForEntityForName:@"FoodInfo"
     inManagedObjectContext:context];
NSAttributeDescription *messageType = [[NSAttributeDescription alloc] init];
[messageType setName:@"photos"];
[messageType setAttributeType:NSTransformableAttributeType];
[imagesForShow addObject:messageType];

I can't even figure out what this is supposed to do. It's completely wrong. You should never be allocating an instance of NSAttributeDescription unless you are constructing a Core Data model on the fly-- which you are not doing and which almost nobody ever does. Creating the new entry is OK. The rest, I don't know. You said that imagesForShow is your array of images, so I don't know why you're also adding an attribute description to the array.

In a more general sense, if newEntry has a transformable attribute named photos and imagesForShow is an NSArray of UIImage objects, then you could do this:

[newEntry setValue:imagesForShow forKey:@"photos"];

This is similar to a line that you have commented out, though it's not clear why it's commented out.

But whatever you do get rid of the code creating the NSAttributeDescription.