2

So I'm trying to save an image taken from UIImagePickerController to NSUserDefaults so I can open it up in an album I generate, but when I call the delegate method to save the picture, I get the error:

[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '<UIImage: 0x1d0bf0>' of class 'UIImage'.  Note that dictionaries and arrays in property lists must also contain only property values.`

The code is as follows:

self.savedPic = [[UIImage alloc] init];
self.savedPic = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[[NSUserDefaults standardUserDefaults] setValue:self.savedPic forKey:[NSString stringWithFormat:@"image_%i",imageCount]];
Chris
  • 7,270
  • 19
  • 66
  • 110

2 Answers2

1

You should save to disk your image and put the name of your image in the NSUserDefaults, then when needed create it :

[UIImage imageNamed:@"nameOfImage.png"]
moxy
  • 1,634
  • 1
  • 11
  • 19
  • Ok. I'm saving the image like this ` UIImageWriteToSavedPhotosAlbum(self.savedPic, self, @selector(savedPic_:didFinishSavingWithError:contextInfo:), nil); ` how do I get the name it's being saved as? – Chris Jun 10 '12 at 10:38
  • the imageNamed method will look for an image on the application's main bundle. In my opinion, using the camera roll is good if you want the user to have it and use it and if you need it again the user has to choose it again from the camera roll but if your application needs to work with it you should copy it in your application main bundle (and maybe when you finished working on it, copy it in the camera roll). – moxy Jun 10 '12 at 11:15
1

It is quite simple, see my codes:

- (UIImage *)backgroundImage {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData* myEncodedImageData = [defaults objectForKey:@"backgroundImageData"];
UIImage* image = [UIImage imageWithData:myEncodedImageData];
return image;
}

- (void)setBackgroundImage:(UIImage *)image {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData* imageData = UIImagePNGRepresentation(image);
[defaults setObject:imageData forKey:@"backgroundImageData"];
[defaults synchronize];
}
flypig
  • 1,260
  • 1
  • 18
  • 23