Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Invasion11

macrumors newbie
Original poster
Jul 27, 2011
6
0
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:

ViewController.H

...
Code:
{
UITextView *textfield;

}
-(IBAction)savetext: (id)sender;
@property (nonatomic, retain) IBOutlet UITextView *textfield;



ViewController.M

-(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?
 
Last edited by a moderator:
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:.
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.