-1

I'm making a painting app, and I currently have the app at a point where it saves drawings, but it still can't load the drawings back into the view once the app has quit or switched views.

I'm saving the image with this:

-(IBAction)saveImage:(id)sender
{
    UIImage *saveImage = drawImage.image;

    NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(saveImage)];


    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:imageData forKey:@"image"];
    [defaults synchronize];

}

Question

How do I load imageData into the view? I'm assuming I can do it in viewDidLoad. Can I?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
2456789
  • 69
  • 1
  • 10

1 Answers1

1

Your saving code looks fine.

To read back the image you would do this:

NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
UIImage* image = [UIImage imageWithData:imageData];

And yes you can do it in viewDidLoad or viewDidAppear/viewWillAppear or anywhere it is appropriate, it really depends on the use case.

Dima
  • 23,484
  • 6
  • 56
  • 83
  • Thanks for your help! This really helps, but I'm getting an issue saying that UIImage* image is an unused variable, which doesn't make sense, because it's being defining it right there. Do you have any idea what might be wrong? Thanks for your help! – 2456789 Jun 25 '12 at 15:38
  • 1
    unused means you're not actually doing anything with it. It's just a warning letting you know you either forgot to use it or that it's redundant. The equivalent of defining `int myNumber = 5;` and then just never using the variable. Once you actually assign it to something else or do something else with it, that warning will go away. – Dima Jun 25 '12 at 15:39
  • I'm sorry to bother you, but I'm still confused. What would I assign that variable to in order to load the saved image? – 2456789 Jun 25 '12 at 17:42
  • You have a `UIImageView` called `drawImage` right? After the code I posted just do `drawImage.image = image;` – Dima Jun 25 '12 at 17:43