initWithContentsOfFile:path] 返回 nil 时的内存管理
[[UIImage alloc] initWithContentsOfFile:path]
当该方法无法初始化图像时返回 nil。然后下一个代码不会释放分配的 UIImage,因为 [image release]
行中的 image 为 nil:
UIImage* image = [[UIImage alloc] initWithContentsOfFile:path];
if(image)
{
....
}
//Here image is nil and not releases allocated UIImage.
[image release];
这真的是内存泄漏吗?
如果init返回nil,要如何释放该对象? 如果我这样做 UIImage* 图像 = [[UIImage 分配] initWithContentsOfFile:path];
并且 image 为零,因为 init 失败, [图像发布]与[无发布]相同。好吧,没有错误,但没有释放任何东西。
[[UIImage alloc] initWithContentsOfFile:path]
return nil when the method can't initialize the image. Then next code is not releasing the allocated UIImage, as image is nil in the [image release]
line:
UIImage* image = [[UIImage alloc] initWithContentsOfFile:path];
if(image)
{
....
}
//Here image is nil and not releases allocated UIImage.
[image release];
Is this really a memory leak?
if init returns nil, how must release the object?
if I do
UIImage* image = [[UIImage alloc] initWithContentsOfFile:path];
and image is nil because init fails,
[image release] is the same as [nil release]. Ok there's not an error, but is not releasing anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
本例中的保留计数与图像是否为零无关。您手动分配了图像
,因此保留计数将为 1,直到您手动释放它,因为您是该对象的唯一所有者。
请参阅 内存管理规则了解有关该主题的更多信息。
Retain count in this example has nothing to do with whether or not the image is nil. You manually allocated the image using
and therefore the retain count will be one until you manually release it, as you are the sole owner of that object.
See Memory Management Rules for more information on the subject.
nil
上的release
是无操作,所以总是可以的。而且它不会泄漏,因为您没有开始的对象。test
本身已经是一个UIImage
对象(尽管您未能在这一行初始化它)。你真的应该总是在同一行(并且在同一个变量上)执行alloc/init - 否则代码逻辑真的很难理解。您的代码仅生成一个对象,然后将其分配给另一个变量。
这是相同的,但更清楚:
这里很明显
test
和image
是同一个对象(因此具有相同的retainCount
) 。每当您释放其中一个对象时,该对象就会消失(除非您之前保留
它)。另请注意,
retainCount
不是您应该依赖或做出太多假设的东西。它充其量也常常具有误导性。release
onnil
is a no-op, so always ok. And it won't leak as you didn't have an object to start with.test
is already anUIImage
object on its own (though you failed to initialize it at this line).You really should always do alloc/init on the same line (and on the same variable) - or the code logic is really hard to follow. Your code generates only one object, and then assigns it to another variable.
This is the same, though much clearer:
Here it is obvious that
test
andimage
are the same object (and hence have the sameretainCount
). Whenever you release one of them, the the object goes away (unless youretain
it before).Please also note that
retainCount
is not something you should rely on or make much assumptions on. It often is misleading at best.