Saving data - does work on Simulator, not on Device

Posted by Peter Hajas on Stack Overflow See other posts from Stack Overflow or by Peter Hajas
Published on 2010-04-21T04:02:52Z Indexed on 2010/04/21 4:43 UTC
Read the original article Hit count: 382

I use NSData to persist an image in my application. I save the image like so (in my App Delegate):

- (void)applicationWillTerminate:(UIApplication *)application
{
    NSLog(@"Saving data");

    NSData *data = UIImagePNGRepresentation([[viewController.myViewController myImage]image]);
    //Write the file out!

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];

    [data writeToFile:path_to_file atomically:YES];
    NSLog(@"Data saved.");
}

and then I load it back like so (in my view controller, under viewDidLoad):

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path_to_file = [documentsDirectory stringByAppendingString:@"lastimage.png"];

if([[NSFileManager defaultManager] fileExistsAtPath:path_to_file])
{
    NSLog(@"Found saved file, loading in image");
    NSData *data = [NSData dataWithContentsOfFile:path_to_file];

    UIImage *temp = [[UIImage alloc] initWithData:data];
    myViewController.myImage.image = temp;
    NSLog(@"Finished loading in image");
}

This code works every time on the simulator, but on the device, it can never seem to load back in the image. I'm pretty sure that it saves out, but I have no view of the filesystem.

Am I doing something weird? Does the simulator have a different way to access its directories than the device?

Thanks!

© Stack Overflow or respective owner

Related posts about nsdata

Related posts about nsfilemanager