我应该使用 __unsafe_unretained 作为临时变量吗?
假设我想创建一个临时变量,例如:
指向另一个长期存在的变量:
__unsafe_unretained UIView *tableHeaderView = self.tableView.tableHeaderView;
指向我刚刚创建的对象。
__unsafe_unretained UIView *tableHeaderView = [[UIView alloc] init];
这些临时变量不需要保留,因为只要临时变量在范围内,它们指向的对象就保证保持正保留计数。那么,我应该将它们声明为__unsafe_unretained
吗?
Let's say I want to create a temporary variable, e.g.:
To point to another long-living variable:
__unsafe_unretained UIView *tableHeaderView = self.tableView.tableHeaderView;
To point to an object I just created.
__unsafe_unretained UIView *tableHeaderView = [[UIView alloc] init];
These temporary variables don't need to be retained because the objects they point to are guaranteed to keep positive retain counts for as long as the temporary variables are in scope. So, should I declare them as __unsafe_unretained
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么系统保留您的临时变量很重要?事实上,你确实想保留它。
考虑:
Why does it matter if the system retains your temp variable? And as a matter of fact, you DO want to retain it.
Consider:
Matt,
ARC 的全部意义就是让你忽略这些问题。事实上,编译器甚至可能不会保留这些实例。
这些问题就让ARC来操心吧。在编译器或静态分析器抱怨之前不要尝试帮助它。 (顺便说一句,您让分析器在每次编译时运行,对吗?它会在您创建问题时发现问题。)
您应该只担心循环中过多的对象创建以及管理大型对象的创建。前者是通过明智地使用@autorelease来处理的。您仍然可以像 ARC 之前那样管理大型项目。
安德鲁
Matt,
The whole point of ARC is to let you ignore these kinds of issues. In fact, the complier may not even retain these instances.
Let ARC worry about these issues. Don't try to help it until the compiler or the static analyzer complain. (BTW, you are letting the analyzer run with every compile, right? It finds problems as you create them.)
You should only worry about excess object creation in loops and managing the creation of large objects. The former is handled by judicious use of
@autorelease
. You still manage large items as you did ante-ARC.Andrew
不会。如果 ARC 保留它,当变量超出范围时它就会释放。
No. If ARC retains it, it will let go when the variable goes out of scope.