user1530460
user1530460

Reputation: 80

Check whether +[UIImage imageNamed:] found an image

I have an long if statement to decide what image to show in a UIImageView. They are all .png files, and I use the code:

if (whatever) {
    image = [UIImage imageNamed: @"imageName.png"];
}

Does anyone know of a way to check to see if the program can find the image? So that if the image does not exist in the program, it can display an error image or something?

Upvotes: 2

Views: 2456

Answers (3)

user529758
user529758

Reputation:

+[UIImage imageNamed:]

will return nil if it couldn't find a corresponding image file. So just check for that:

UIImage *image = [UIImage imageNamed:@"foo.png"];
if (image == nil)
{
    [self displayErrorMessage];
}

Upvotes: 7

jscs
jscs

Reputation: 64002

First, I'd suggest using a dictionary instead of a long if. You can key each image name by whatever. If whatever isn't currently an object, make an enum that will encapsulate that information and use NSNumbers to box the values of the enum.

Then, you can check for nil when you try to retrieve the image. imageNamed: uses nil to indicate failure, so:

if( !image ){
    // No image found
}

Upvotes: 0

Farcaller
Farcaller

Reputation: 3070

The shortest snippet would be

image = [UIImage imageNamed:@"imageName"] ? : [UIImage imageNamed:@"fallback_image"]

but do you really want such code?

Make another check:

if (whatever) {
    image = [UIImage imageNamed: @"imageName.png"];
    if(image == nil) {
        image = [UIImage imageNamed: @"fallback_image"];
    }
}

it still can be shorted, like

if(! (image = [UIImage imageNamed: @"imageName.png"]) ) {
    ...
}

but you're toying with readability here.

Upvotes: 3

Related Questions