开发者

mem allocation with imageNamed

I want to display some images, when image is not available I want to 开发者_JAVA技巧show a default one. When using the analyze functionality I get warnings about a potential leak. I do under stand that when using imageNamed there is no memory allocated, what would be a nice workaround ? See below a part of my code

if (!isMyFileThere){
    image = [UIImage imageNamed:@"default.png"];            
}
else{
    image = [[UIImage alloc] initWithContentsOfFile:pngFilePath];
}


This is autoreleased

 image = [UIImage imageNamed:@"default.png"];

This is not

image = [[UIImage alloc] initWithContentsOfFile:pngFilePath];

You need to do this :

image = [[[UIImage alloc] initWithContentsOfFile:pngFilePath] autorelease];

The rule is if your method name begins with alloc, new, copy or muteableCopy you own it and need to release it yourself, either with release or with autorelease. Anything else isn't yours so you mustn't release it.

If you call retain on an object, you must release (or autorelease) it the same number of times :)


image = [[UIImage alloc] initWithContentsOfFile:pngFilePath]; You have done a alloc and you have to now release it, which is a potential leak if you don't. The other statement is autoreleased object.


If you want to object to stay until you release it manually you should use retain, autorelease adds the object to the current NSAutorelease pool which gets drained at the end of each run loop iteration. if you attempt to use a freed object your program will crash.

in iOS 5.0 if you enable ARC you won't need to use "retain", "autorelease" or "release" anymore. those are added by the compiler automatically.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜