释放通过 imageNamed 加载的保留 UIImage 属性?
在我的类对象中,我为 UIImage
定义了一个 (nonatomic,retain)
属性。 我用通过加载的图像分配了此属性
[UIImage imageNamed:@"file.png"];
如果在某个时候我想将此属性重新分配给另一个图像,我是否必须释放先前的引用?
我很困惑,因为通过保留属性,我知道我应该释放它。 但是因为 imageNamed:
是一种方便的方法(不使用 alloc),所以我不确定这里应用什么规则。
感谢您的见解!
In my class object i've defined a (nonatomic, retain)
property for UIImage
.
I assigned this property with an image loaded via
[UIImage imageNamed:@"file.png"];
If at some point I want to reassign this property to another image, should I have to release the prior reference?
I am confused because by the retain property I know i should release it.
But because imageNamed:
is a convenience method (does not use alloc), im not sure what rule to apply here.
Thanks for the insight!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正确,Florin...但是根据上面的讨论,如果一个人使用一个 setter 来(通过合成或手动)执行“保留”,那么就不需要额外的保留。
换句话说,以下内容是正确的(并且没有内存泄漏),恕我直言,我是对的吗?我认为这就是这个问题的初衷……我也想确定一下。 ;-) 谢谢!
Correct, Florin... but per the discussion above, if one is using a setter for the property that (either via synthesize, or manually) does the "retain", then there's no need for the extra retain.
In other words, the following would be correct (and free of memory-leaks), IMHO, am I right? I think this was the original intent of the question... and I'd also like to be certain. ;-) thx!
图像将按照命名规则自动发布返回给您。通过 setter 将其分配给具有保留属性的属性将保留它。通过 setter 将另一个图像分配给属性将释放旧图像并保留新图像。
The image is returned to you autoreleased as per the naming rules. Assigning it to a property with a retain attribute via the setter will retain it. Assigning another image to the property via the setter will release the old image and retain the new one.
当您使用
nonatomic
& 定义属性时retain
,它会为您创建一个如下所示的 setter:如您所见,它在保留新值之前释放以前的值。
在您的特定情况下,当您将
-[UIImage imageNamed:]
返回的自动释放图像分配给属性时,将自动保留该图像,然后在您分配另一个图像(或nil
) 到属性。When you define a property with
nonatomic
&retain
, it creates a setter for you that looks like this:As you can see, it releases the previous value before retaining the new value.
In your particular case, the autoreleased image returned by
-[UIImage imageNamed:]
will be automatically retained when you assign it to the property, and then automatically released when you assign another image (ornil
) to the property.来自 文档:
这意味着,如果您不想再保留它,则应该释放它(假设您已经保留了它)。
From the docs:
The implication being that if you no longer want to hold onto it, you should release it (assuming you've retained it).
您应该释放所有保留的对象,但是当您定义图像对象时,我相信您的代码应该如下所示:
You should release all the objects you're retaining, however when you define your image object, I believe your code should look like this: