Reputation: 24416
I have an array of NSString
s:
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
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
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
AND
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
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
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