Objective-C 中的访问器调用
两者之间有什么区别:
self.ivar;
self->ivar;
ivar;
在 Objective C 中访问 ivar
的方式。
何时调用 setter?
What is the difference between:
self.ivar;
self->ivar;
ivar;
Way of accessing ivar
's in objective C.
When will the setter be invoked?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
self->ivar
和ivar
直接访问实例变量。不调用访问器方法。foo = self.ivar
将调用[self ivar]
访问器方法(或@property
的getter=
方法(如果您以这种方式指定的话)self.ivar = foo;
将调用[self setIvar:foo]
访问方法(或@property
代码>的setter=
方法)。self->ivar
andivar
access the instance variable directly. The accessor method is not called.foo = self.ivar
will call the[self ivar]
accessor method (or the@property
'sgetter=
method if you specify it that way)self.ivar = foo;
wil call the[self setIvar:foo]
access method (or the@property
'ssetter=
method).在非 ARC 环境中,
self->ivar
和ivar
均不包含 Objective-C 调用,而是从内存中设置和获取标量。点语法(例如self.ivar
或[self setIvar:]
)对可以处理内存管理等的 setter/getter 方法进行 Objective-C 调用Apple 的 @property 包括 @synthesize,它为您编写这些方法实现。在 ARC 环境中,属性和手动分配 ivar 都包含一些内存管理逻辑。甚至在优化的 ARC 环境中,@property 的使用可能只是使用 ARC 的内置逻辑,而不是尽可能进行 Objective-C 调用。
In non-ARC environments, the both
self->ivar
, andivar
include no Objective-C calls, and instead set and get scalars from memory. The dot syntax, (e.g.self.ivar
, or[self setIvar:]
) makes an Objective-C call to a setter/getter method that can handle memory management, etc. Apple's @property includes @synthesize, which writes these method implementations for you.In ARC environments, both properties and manually assigning an ivar include some memory management logic. It may even be that, in optimized ARC environments, the use of @property simply uses ARCs built-in logic, rather than making Objective-C calls whenever possible.