Search code examples
objective-ciosnsfilemanager

NSFileManager fileExistsAtPath only works for absolute paths


I have a bunch of customer images (named [code].png) in a folder, but some customers do not have images, so I'd like to display a placeholder.

I'm checking the existence of the image [code].png, and if it exists I display that one, else I display the placeholder. However, fileExistsAtPath always returns false, even for images that exist.

NSFileManager *m    = [NSFileManager defaultManager];
NSString *imagePath = [NSString stringWithFormat:@"%@.png",code];
if ([m fileExistsAtPath:imagePath])
    self.detailViewController.imageFrame.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png",code]];
else
    self.detailViewController.imageFrame.image = [UIImage imageNamed:@"customer_large.png"];

This always displays customer_large.

However, if I change the imagePath to an absolute path to the image and leave the displayed image as a relative filename, the boolean works correctly, and the image displayed works as well.

This proves that the filename I am checking for does exist, as the image displays, but I'm obviously missing something in terms of fileExistsAtPath as it returns false when the program has proven the file to exist.


Solution

  • Since the image is stored in the project, and not the documents directory, I would not use NSFileManager at all.

    Instead, use [UIImage imageNamed:@"IMAGE_FILENAME"] and see if it returns nil. If it does, then use the placeholder.

    Here is a code snippet:

    UIImage *possibleImage = [UIImage imageNamed:@"IMAGE_FILENAME"];
    if (possibleImage) {
       self.detailViewController.imageFrame.image = possibleImage;
    } else {
       self.detailViewController.imageFrame.image = [UIImage imageNamed:@"customer_large.png"];
    }