问题描述
所以在我看到的一些代码中,他们直接访问对象 ivar 而不是使用 accessors .使用它们代替访问器有什么好处?
So in some of the codes I see, they access an objects ivar directly instead of using accessors . What are the advantages of using them instead of accessors?
那怎么办
thing = object->ivar
与此不同?
thing = object.ivar
谢谢.
推荐答案
首先让我说,我完全讨厌 Objective-C 点符号.它为了简洁而牺牲了可理解性,这是一件坏事.事实上,这里的其他两个答案都显示了点符号引入的混淆类型的证据.
First let me say, I totally loathe the Objective-C dot notation. It sacrifices understandability for brevity and that is a bad thing. In fact, the other two answers here both show evidence of the kind of confusion dot notation introduces.
停止咆哮,我现在尝试回答这个问题.
Having got the rant out of the way, I'll now try to answer the question.
在底层,Objective-C 对象被实现为 C 结构的指针.这就是为什么
Under the hood, Objective-C objects are implemented as pointers to C structs. This is why
obj->ivar
有时有效.鉴于它是一个 C 结构
sometimes works. Given that it's a C struct
(*obj).ivar
(*obj).ivar
也应该完全符合您对 C 的期望.话虽如此,您可以将 ivars 设为私有或受保护,在这种情况下,在它们可见的范围之外使用上述内容会导致编译器错误.
should also work exactly as you would expect for C. Having said that, you can make ivars private or protected, in which case using the above outside a scope where they are visible will cause a compiler error.
点运算符在应用于 Objective-C 对象(别忘了这是一个指针)时具有完全不同的含义.这是向对象发送访问器消息的语法糖,意思是:
The dot operator when applied to an Objective-C object (which is a pointer don't forget) has a totally different meaning. It's syntactic sugar for sending an accessor message to the object meaning that:
foo = obj.property;
obj.property = foo;
与
foo = [obj property];
[obj setProperty: foo];
这就是点符号的全部内容.如果您通过代码将第一种形式的所有实例更改为第二种形式的实例,那么您已经完成了编译器使用点表示法所做的一切.
That is all there is to dot notation. If you go through your code changing all instances of the first form to instances of the second form, you have done everything the compiler does wrt dot notation.
特别是
- 您不需要声明的
@property
即可使用点表示法.您可以以传统方式将 set 和 get 访问器声明为 Objective C 方法,尽管对于逻辑属性的事物使用@property
声明绝对是最佳实践. - 您不需要支持实例变量.您的 getter 和 setter 没有理由无法计算值.
- you do not need a declared
@property
to use dot notation. You can declare the set and get accessors in the traditional way as Objective C methods, although it is definitely best practice to use@property
declarations for things that are logically properties. - you do not need a backing instance variable. There's no reason why your getters and setters can't calculate values.
综上所述,obj->ivar
和 obj.ivar
的主要区别在于前者直接修改 ivar,后者调用访问器,这意味着后者可以做任何需要的内存管理工作(保留、释放、复制等),也可以调用键值观察.
Given the above, the major difference between obj->ivar
and obj.ivar
is that the former modifies the ivar directly and latter invokes an accessor, this means that the latter can do any memory management stuff needed (retains, releases, copies etc) and can also invoke key value observing.
这篇关于直接访问 ivars 与使用访问器有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!