views:

296

answers:

3

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?

+5  A: 

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];
Jason Coco
Also, note that imageNamed will cache image in memory for later, while initWithContentsOfFile won't - use latter if it's one shot thing and memory is important.
Rudi
initWithContentsOfFile will, the only one that won't is initWithData.
Jason Coco
The image file may not be in the bundle's root directory. If that's the case, use [[NSBundle mainBundle] pathForResource:@"file1" ofType:@"jpg" inDirectory:@"directory/or_subdirectory"] as the path.
Alex
A: 

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

UIImage* image = [[UIImage imageNamed:fileName] retain];
DevDevDev
I can't see any reason to put a retain there. In your simple example you are assigning the return value to a variable in the local scope, so retaining it is almost always an error. It's better to place the retain calls where they are needed (like when assigning to a variable in the global scope or copying the variable to a pointer passed to the method, etc.)
Jason Coco
The OP has a retain counter of +1, as such so should the response code.
DevDevDev
The OP is clearly new to Objective-C and the Foundation framework. He/she may or may not be releasing that method call later, but there is almost never any reason for the line in your example, and IMHO, it's better not to present examples that lead to bad habits.
Jason Coco
Yes i suppose you're right.
DevDevDev
A: 

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.

Devin Ceartas