使用 imageNamed 进行内存分配
我想显示一些图像,当图像不可用时我想显示默认图像。 使用分析功能时,我收到有关潜在泄漏的警告。 我确实明白,使用 imageNamed 时没有分配内存,什么是一个很好的解决方法? 请参阅下面我的代码的一部分
if (!isMyFileThere){
image = [UIImage imageNamed:@"default.png"];
}
else{
image = [[UIImage alloc] initWithContentsOfFile:pngFilePath];
}
I want to display some images, when image is not available I want to 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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是自动释放的
这不是
您需要这样做:
规则是您的方法名称是否以
alloc
、new
、copy
或开头>muteableCopy
您拥有它,需要自己释放它,可以使用release
或使用autorelease
。其他任何东西都不是你的,所以你不能释放它。如果您对某个对象调用
retain
,则必须对其进行相同次数的release
(或autorelease
) :)This is autoreleased
This is not
You need to do this :
The rule is if your method name begins with
alloc
,new
,copy
ormuteableCopy
you own it and need to release it yourself, either withrelease
or withautorelease
. Anything else isn't yours so you mustn't release it.If you call
retain
on an object, you mustrelease
(orautorelease
) it the same number of times :)image = [[UIImage alloc] initWithContentsOfFile:pngFilePath];
您已经完成了分配,现在必须释放它,如果不这样做,可能会导致泄漏。另一条语句是自动释放对象。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.如果你想让对象保留到手动释放它为止,你应该使用retain,autorelease将对象添加到当前的NSAutorelease池中,该池在每次运行循环迭代结束时被耗尽。如果您尝试使用已释放的对象,您的程序将崩溃。
在 iOS 5.0 中,如果启用 ARC,您将不再需要使用“retain”、“autorelease”或“release”。这些是由编译器自动添加的。
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.