cannyboy
cannyboy

Reputation: 24416

How to find out whether an image exists within a bundle?

I have an array of NSStrings:

Flower
Car
Tree
Cat
Shoe

Some of these strings have images associated with them; some don't. I can build an image name by appending .png to the name (e.g. Flower.png).

How do I check whether that image actually exists within the bundle before I try to load it into the view?

Upvotes: 5

Views: 7294

Answers (4)

budiDino
budiDino

Reputation: 13527

I don't even add the ".png" to the file name and it works:

NSArray *images = @[@"Flower", @"Car", @"Tree", @"Cat", @"Shoe"];

if ([UIImage imageNamed:images[0]]){
        // there is a flower image
    } else {
        // no flowers for you
    }
}

Upvotes: 0

sam_smith
sam_smith

Reputation: 6093

I would assign the image as a variable, then you can check if the image exists:

UIImage * flowerImage = [UIImage imageNamed:@"Flower.png"];

if (flowerImage) {
    // Do something
}
else {
    // Do something else
}

In the accepted answer we are checking to see if the picture equals an image with a specific name. This could go wrong as we will return no if

  • The image Flower.png doesn't exist

AND

  • The image Flower.png does exist but flowerImage is set to a different image meaning they are not equal

Assigning a variable to the image and then checking if the variable is assigned or not will return us a definite yes or no depending on whether Flower.png exists

Upvotes: 3

Emil
Emil

Reputation: 590

This should also work, and is a bit shorter:

if (flowerImage = [UIImage imageNamed:@"Flower.png"])
{
   ... // do something here
}
else
{   
   ... // image does not exist
}

The imageNamed: method will look in your main bundle for the png file.

Upvotes: 18

Steve Harrison
Steve Harrison

Reputation: 125470

Just load the resource and check whether it is nil or not:

NSString* myImagePath = [[NSBundle mainBundle] pathForResource:@"MyImage" ofType:@"jpg"];
if (myImagePath != nil) {
    // Do something with image...
}

Upvotes: 6

Related Questions