What is the way for image in iphone design

I have this piece of object code c:

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

file_name is set to "file1.jpg"

However, when I run the code, the image is set to nil.

I know the file exists. I guess it has something to do with the path.

Which way should i use?

+4
source share
3 answers

The easiest way is to use imageNamed: as follows:

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

If for some reason you need to use initWithContentsOfFile: you need to get the path from the package, for example:

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

To get the same behavior as your code so that your image is not auto-implemented

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

And, of course, the image should be included - if you drag it into your project in Xcode and select a copy of the resource from the parameters, it just needs to find it in order.

0
source

All Articles