How do I know if an image exists inside a package?

I have an NSStrings array :

Flower
Car
Tree
Cat
Shoe

Some of these lines have images associated with them; some are not. I can create an image name by adding .pngto the name (for example, Flower.png).

How to check if this image really exists in a package before trying to load it into a view?

+5
source share
4 answers

This should also work and a little shorter:

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

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

+19
source

, nil :

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

, , :

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

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

, . , ,

  • Flower.png

  • Flower.png , flowerImage , , .

, , , , Flower.png

+3

".png" , :

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

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

All Articles