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?
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.
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...
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With