How can I save an image in xcode?

Discussion in 'iOS Programming' started by Invasion11, Oct 9, 2011.

  1. Invasion11, Oct 9, 2011
    Last edited by a moderator: Oct 9, 2011

    Invasion11 macrumors newbie

    Jul 27, 2011
    I'm wanting to be able to import an image to an imageview, then save it, and when relaunching the app it's still there. I know how to "save data" with text only:


    UITextView *textfield;
    -(IBAction)savetext: (id)sender;
    @property (nonatomic, retain) IBOutlet UITextView *textfield;
    -(IBAction)savetext: (id)sender {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:textfield.text forKey:@"text"];
        [defaults synchronize];
    - (void)viewDidLoad {
     [super viewDidLoad];
          textfield.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"text"];

    If I try to do this with an image, it doesn't work and it gives me an error. Can anyone please help me?
  2. jiminaus macrumors 65816


    Dec 16, 2010
    You need to "freeze dry" the UIImage object as an NSData object. You can use the UIImageJPEGRepresentation or UIImagePNGRepresentation functions to get the image as either a jpeg or a png.

    Once you've freeze dried the image, you can use NSUserDefault's setObject:forKey: so store the image bytes.

    To retrieve the image bytes, use NSUserDefault's data:forKey:. This will get you back the NSData object.

    To "reconstitute" the UIImage object from the NSData object, use UIImage's imageWithData: or initWithData:.
  3. North Bronson macrumors 6502

    Oct 31, 2007
    San José
    NSUserDefaults is not a good place for large blobs of data. A better approach would be to save the image as data, write that data to your sandbox cache directory, then save the file URL to your NSUserDefaults.

    You can also look at the ImageIO functions for exporting bitmap images to data. These functions give you a little more options and flexibility than the UIKit functions do.

Share This Page