I am using UIImage to plot a png. I have getting a weird behavior that I cannot understand.
The following piece of code results in a nil im reference and thus prints "PROBLEM!"
UIImage *im = [[UIImage alloc] initWithContentsOfFile:@"tree.png"];开发者_JAVA技巧
if (nil==im)
NSLog(@"PROBLEM! IMAGE NOT LOADED\n");
else
NSLog(@"OK - IMAGE LOADED\n");
This piece of code works finely:
UIImage *im = [UIImage alloc];
[im initWithContentsOfFile:@"tree.png"];
if (nil==im)
NSLog(@"PROBLEM! IMAGE NOT LOADED\n");
else
NSLog(@"OK - IMAGE LOADED\n");
What am I missing?
[[UIImage alloc] initWithContentsOfFile:@"tree.png"];
will return to you image if image /tree.png
exist. But it doesn't exist. You should pass to initWithContentsOfFile
full path, not only name of file.
Now, second one code works because of [UIImage alloc]
return some reference that is not initialized. In next line your are trying to init it with [im initWithContentsOfFile:@"tree.png"];
but you've forgotten to save returned value in im
, like this: im = [im initWithContentsOfFile:@"tree.png"];
.
If image tree.png
is saved in your bundle, then you can use such approach : UIImage *im = [UIImage imageNamed:@"tree.png"];
or such:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"tree" ofType:@"png"];
UIImage *im = [[UIImage alloc] initWithContentsOfFile:filePath];
Is the image in your bundle and is it a PNG image? The UIImage Documentation mentions the following when using initWithContentsOfFile:
An initialized UIImage object, or nil if the method could not find the file or initialize the image from its contents.
Also, since you are using the UIImage locally I assume from your code, you could just use the imageNamed:
class method like so and it will search for the image in your main bundle:
UIImage *im = [UIImage imageNamed:@"tree.png"];
if (nil==im)
NSLog(@"PROBLEM! IMAGE NOT LOADED\n");
else
NSLog(@"OK - IMAGE LOADED\n");
try:
NSString *path = [[NSBundle mainBundle] pathForResource:@"tree" withExtension:@"png"];
UIImage *im = [[UIImage alloc] initWithContentsOfFile:path];
to load the image from your application bundle.
BTW, your second piece of code is potentially dangerous. Actually initWithContentsOfFile:
calls autorelease
for the object, if file is not found. And if you tried to access image after a while, it would be an error (EXC_BAD_ACCESS).
So that you should always use init
methods in pair with alloc
and do not forget to release
is somewhere.
精彩评论