Reputation: 183
Trying to add an image to a database using core data. A view controller is used for the user to enter text fields and an image to the database. The user selects an image using UIImagePickerController. Code is:
- (void) add
{
NSManagedObjectContext *context = [app managedObjectContext];
Exercises *exercises = [NSEntityDescription insertNewObjectForEntityForName:@"Exercises" inManagedObjectContext:context];
exercises.name = name.text;
exercises.difficulty = difficulty.text;
exercises.type = type.text;
exercises.instructions = instructions.text;
NSData* image1 = [NSData dataWithData:UIImagePNGRepresentation(imageView.image)];
[NSManagedObject setValue:image1 forKey:@"imageView"];
[self dismissViewControllerAnimated:YES completion:nil];
Error is Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imageView.' What should the key be? Am I even going about this the right way? By the way, saving and retrieving of text works fine. My only issue with adding images.
Upvotes: 0
Views: 978
Reputation: 124
Try saving your image in document directory and add the path of image in the database.
You can access the Image using :
[[UIImageView alloc]initWithImage:[UIImage imageWithData:
[NSData dataWithContentsOfFile:@"PathStoredInDatabase"]]];
Upvotes: 3
Reputation: 100622
The call:
[NSManagedObject setValue:image1 forKey:@"imageView"];
attempts to call setValue:forKey:
on the class NSManagedObject
. That class does not implement that method so it raises an exception.
Probably you wanted to call it on exercises
, the instance of NSManagedObject
that you've just created — does it have a data attribute called imageView
?
In both style and performance terms, the dot notation to access a specific setter is preferred, as you've used for all the other properties, but it's unlikely to be much of a problem compared to the PNG encode it sits next to so I wouldn't worry about it.
Upvotes: 4