Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
cannyboy Avatar asked Jun 10 '10 04:06

cannyboy


3 Answers

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.

like image 153
Emil Avatar answered Oct 15 '22 14:10

Emil


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...
}
like image 30
Steve Harrison Avatar answered Oct 15 '22 14:10

Steve Harrison


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

like image 3
sam_smith Avatar answered Oct 15 '22 14:10

sam_smith