关于使用 ivar 变量而不是 getters 的好处
虽然我使用 Objective-C 语法,但问题语言不可知。
假设以下声明
@synthesize activities = _activities;
self.activities
将调用 getter,并且 _activities
将检查为已分配的值。据我了解,此分配的主要好处是可以清楚地区分何时调用 setter 以及何时调用局部变量。
虽然这很好,但是使用 ivar 与使用 getter 方法相比,真正有形的好处是什么?
我能想到一个,其他的还有什么?
- 我认为使用 ivar 比调用 getter 更快,但与触摸事件相比,差异可以忽略不计。
Though i am using Objective-C syntax, the question language agnostic.
Assuming the following declaration
@synthesize activities = _activities;
self.activities
will call the getter and _activities
will check for the value which was already assigned. The main benefit of this assignment, as i understand it, is to clearly differentiate when setter is called and when local variables is called instead.
While this is nice, what is the real tangible benefit of using ivar vs using getter methods?
I can think of one, what are others?
- I suppose using ivar is faster then calling the getter, but compared with what goes on with touch events, the difference is negligible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接访问实例变量意味着绕过合成访问器提供的任何原子性保护和内存管理。如果您在执行此操作时很清楚,则可以更轻松地审核此类访问,以确保您自己负责类行为的这些方面。
Accessing the instance variables directly means circumventing any atomicity protection and memory management supplied by the synthesized accessors. If it's clear when you're doing that, it's easier to audit such access to ensure that you're looking after these aspects of the class's behaviour yourself.