视图控制器的 var 是否应该在 viewDidUnload 中保留属性释放?
看看Apple的ToolbarSearch示例,我发现他们的视图控制器的searchBar变量有一个retain属性,它执行以下操作:
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 400.0, 0.0)];
在控制器的dealloc中,searchBar被释放。然而,它的viewDidUnload并没有释放,只是将searchBar变量设置为nil。
我认为 alloc 会增加保留计数,并且变量的保留属性还会增加计数。如果这是真的,那岂不是意味着searchBar需要在viewDidUnload中释放?
Looking at Apple's ToolbarSearch example, I see that their view controller's searchBar variable has a retain property and it does this:
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 400.0, 0.0)];
in the controller's dealloc, the searchBar is released. However, its viewDidUnload doesn't release but just sets the searchBar variable to nil.
I thought the alloc increments the retain count and that the retain property of the variable additionally increments the count. If this is true, wouldn't it mean the searchBar needs to be released in viewDidUnload?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Joey -
合成属性的“保留”属性仅在调用变异器时适用。因此,如果外部类调用:
viewController 将调用 mySearchBar 上的保留。由于
不经过变元(它只是直接修改实例变量 searchBar),因此只有其中一个对象的保留计数(来自 alloc)。
因此,示例中的保留/释放计数是正确的。在执行 dealloc 时,alloc 为 +1,release 为 -1。
如果您对 -viewDidUnload 和 -dealloc 之间的区别感到困惑,这里有一个很好的解释:我到底必须在 viewDidUnload 中做什么?
Joey -
The 'retain' attribute of a synthesized property only applies when the mutator is called. So, if an external class called:
The viewController would call retain on mySearchBar. Since
doesn't go through the mutator (it just modifies the instance variable searchBar directly), there's only a retain count of one of the object (from alloc).
So, the retain/release count in the example is correct. +1 from alloc, -1 from release in the implementation of dealloc.
If you're confused about the difference between -viewDidUnload and -dealloc, here's a great explanation: What exactly must I do in viewDidUnload?
那不是真的。您引用的
-viewDidUnload
方法有以下行:That is Passing
nil
to the setter for thesearchBar
property ,相当于:The setter对于
retain
属性,将release
发送到旧值,将retain
发送到新值。That's not true. The
-viewDidUnload
method you refer to has the line:That is passing
nil
to the setter for thesearchBar
property and is equivalent to:The setter for a
retain
property sendsrelease
to the old value andretain
to the new one.