GeoffreyF67
GeoffreyF67

Reputation: 11141

What is the path for an image in iphone development

I have this snippet of objective c code:

UIImage *image = [ [UIImage alloc] initWithContentsOfFile:fileName];

fileName is set to "file1.jpg"

When I run the code, however, image is set to nil.

I know the file does exist I am guessing it has something to do with the path.

What path should I be using?

Upvotes: 4

Views: 7810

Answers (3)

Jason Coco
Jason Coco

Reputation: 78353

The easiest thing to use is imageNamed: like this:

UIImage* theImage = [UIImage imageNamed:@"file1.jpg"];

If you need to use initWithContentsOfFile: for some reason, you need to get the path from the bundle, like this:

NSString* path = [[NSBundle mainBundle] pathForResource:@"file1" ofType:@"jpg"];
UIImage* theImage = [[UIImage alloc] initWithContentsOfFile:path];

Upvotes: 14

Devin Ceartas
Devin Ceartas

Reputation: 4829

And, of course, the image has to be in the bundle -- if you drag it into your project in XCode and choose copy the resource from the options, it should just find it OK.

Upvotes: 0

DevDevDev
DevDevDev

Reputation: 5177

To get the same behavior as your code so that your image is not autoreleased

UIImage* image = [[UIImage imageNamed:fileName] retain];

Upvotes: 0

Related Questions