Why can my data write to a file on the iPhone simulator, but not on my device?

advertisements

I have the following code that saves the users sketch data to a file...

//Auto Save the sketch
NSString *filename = [NSString stringWithFormat:@"%@.png", sketchID];
CGImageRef imageRef = CGBitmapContextCreateImage(paintView.canvas.mBitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filename atomically:YES];

CGImageRelease(imageRef);
[image release];

the SketchID is a unique alphanumeric value, so an example of the filename I'm saving to is "p1.png". The code I use to read the file is...

//Load the sketch where the user left off, if there is one
if(fileName != nil)
{
    UIImage* image = [UIImage imageWithContentsOfFile:fileName];    

    if(image != nil)
    {
          .
          .

This code seems to work fine when running on the simulator, but when I run it on the device, the fails to load the image. I new to iOS development and I'm still learning how files are stored. My questions are...

  1. Why would saving/loading the file work on the simulator, but not the device?
  2. When I create the filename that I want to save the data to, do I need to also include a path to a specific directory on the iPhone where the data should be properly stored? Or should "p1.png" work fine when I call the writeToFile: method? And what about the imageWithContentsOfFile: method?

Thanks so much in advance for your help!


Why would saving/loading the file work on the simulator, but not the device?

There are tons of reasons, but the most common is trying to write to a location that isn't writable on the device, and the most common reason for that is writing to the application bundle itself.

All iPhone apps are "sandboxed" on the device, meaning they cannot access the filesystem outside of the directory the application is installed into.

When I create the filename that I want to save the data to, do I need to also include a path to a specific directory on the iPhone where the data should be properly stored? Or should "p1.png" work fine when I call the writeToFile: method? And what about the imageWithContentsOfFile: method?

You can write to your application's temp directory (if you just need a temporarily place to put something during a run) or the Documents directory (if you need to store something more permanently, and also have it backed up by iTunes).

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