Objective-C 内存管理:设置保留属性时会发生什么?
我想了解以下代码行的内存管理含义:
// in tableView:cellForRowAtIndexPath
cell.accessoryView = [[UIImageView alloc] initWithImage:
[UIImage imageNamed:@"test.png"];
我正在调用 alloc
这通常意味着我在某处调用 release
。 UITableViewCell
的 accessoryView
setter 属性是 retain
所以(我认为)单元格将“取得 UIImageView 的所有权” 。 上面这行代码在内存管理方面到底发生了什么?
I'd like to understand the memory management implications of the following line of code:
// in tableView:cellForRowAtIndexPath
cell.accessoryView = [[UIImageView alloc] initWithImage:
[UIImage imageNamed:@"test.png"];
I'm calling alloc
which usually means I call release
somewhere. The UITableViewCell
's accessoryView
setter property is retain
so (I think) the cell will "take ownership" of the of the UIImageView
. What exactly is happening in the above line of code in regards to memory management?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一:+alloc 保留 UIImageView(或者,“您从 UIImageView 的所有权开始”)
第二:+imageNamed 自动释放 UIImage(或者,“+imageNamed 不给您 UIImage 的所有权”)
第三: AccessoriesView 保留 UIImageView (或者,“附件视图取得 UIImageView 的所有权”)
由于您现在有 UIImageView 的两个所有者,这可能是泄漏,除非您故意保留它以便以后使用,并进行相应的管理。
First: +alloc retains the UIImageView (or, alternately, "you start with ownership of the UIImageView")
Second: +imageNamed autoreleases the UIImage (or, "+imageNamed does not give you ownership of the UIImage")
Third: the setter for accessoryView retains the UIImageView (or, "the accessory view takes ownership of the UIImageView")
Since you now have two owners for the UIImageView, that's probably a leak unless you're intentionally keeping it around to use later, and managing it accordingly.
可以这样想:您正在调用 alloc/init,因此您拥有它。当您不想再拥有它时,您必须释放它。
您可以假设 cell.accessoryView 拥有所有权,除非文档另有说明(如委托),因此一旦将其分配给 cell.accessoryView,您可能不再需要拥有它。你应该释放它。
总之,该行至少保留两次:一次与 alloc/init 一起使用,至少一次与 cell.accessoryView 的分配一起使用。您只负责一个版本,即 alloc/init 版本。
Think of it this way: you're calling alloc/init, so you own it. You must release it when you no longer want to own it.
You can assume that cell.accessoryView takes ownership unless the docs say otherwise (like with delegates), so once you assign it to cell.accessoryView, you probably don't need to own it anymore. You should release it.
In summary, that line is retaining at least twice: once with the alloc/init and at least once with the assignment to cell.accessoryView. You are only responsible for one release, the one for alloc/init.
如果你不在某个地方释放视图,那么它就会被泄露。所以你可能想做
或者你也可以做
If you don't release the view somewhere then it will be leaked. So you might want to do
or you could also do