Objective-c 现代运行时在接口块中使用属性和 ivars
我看过代码示例(来自《Beginning iPhone 4 Development》一书),其中它们都在接口块内声明 ivars,然后声明相同的属性。像这样:
@interface ViewController : UIViewController {
UITableView *table;
}
@property (nonatomic, retain) IBOutlet UITableView *table;
这样做的目的/好处是什么?据我了解,使用现代运行时版本(iPhone 和 64 位 OS X 应用程序),您只需要声明属性,并且可以省略在接口块内声明 ivars。根据 这个在类似线程中的答案将用于调试目的。但是,除了调试之外,您使用这种方法还有其他好处吗?
干杯,
彼得
I've seen code examples (from the book Beginning iPhone 4 Development) where they both declare ivars inside the interface block and then declare properties for the same. Like this:
@interface ViewController : UIViewController {
UITableView *table;
}
@property (nonatomic, retain) IBOutlet UITableView *table;
What would be the purpose/benefit of this? As I understand that with the modern runtime version (iPhone and 64-bit OS X applications) you only need to declare properties and can leave out declaring the ivars inside the interface block. According to this answer in a similair thread it would be for debugging purposes. But are there any other benefits except for debugging that you would use this approach?
Cheers,
Peter
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
显式声明 ivars 使您可以在内部使用 ivar 的专用类型。
一个典型的例子是内部可变的对象,可以以只读、不可变的方式从外部访问。
示例:
当然,从
bars
属性返回的对象并不是真正不可变的。但重点是 API 并没有透露它的可变性。请注意,我使用了新奇的 private-ivars-in-implementation 风格。它取决于现代运行时以及 clang 编译器。
Explicitly declaring ivars gives you the possibility to internally use a specialized type for the ivar.
A typical example is an internally mutable object that can be accessed from outside in a readonly, immutable way.
Example:
Of course the object returned from the
bars
property is not really immutable. But the point is that the API does not reveal its mutability.Note that I used the fancy new private-ivars-in-implementation style. It's depending on the modern runtime as well as the clang compiler.
一些程序员喜欢用稍微不同的名称来定义他们的 iVar,以区分直接访问和 KVC 访问。例如:
在 .h
和 .m
中,您可以使用
_table
直接访问 iVar,但可以使用[self table]
使用合成的 setter 和 getterSome programmers like to define their iVars with a slightly different name to differentiate between direct access and KVC access. For example:
in the .h
and in the .m
this way you directly access the iVar using
_table
but you use the synthesized setters and getters using[self table]
我明确声明 ivars 是为了:
“一切都是读/写属性”从根本上来说是有缺陷的。
i declare the ivars explicitly for:
"everything as a read/write property" is fundamentally flawed ood.