开发者

Saving data - does work on Simulator, not on Device

开发者 https://www.devze.com 2022-12-28 02:50 出处:网络
I use NSData to persist an image in my application. I save the image like so (in my App Delegate): - (void)applicationWillTerminate:(UIApplication *)application

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 p开发者_运维百科retty 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!


Aha! Nailed it!

I'm writing this so someone else pulling their hair doesn't sit there staring at code, wondering why it doesn't work :)

The problematic line is this one:

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

It should look like this:

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

The reason for this is, without it, you'd get something along the lines of /Files/Documentslastimage.png instead of /Files/Documents/lastimage.png, as the path component appending takes care of the slashes for you. I hope this helps someone else in the future!

0

精彩评论

暂无评论...
验证码 换一张
取 消