【发布时间】:2010-12-27 16:34:19
【问题描述】:
我一直认为不能在类别中声明对象属性。 直到我的伙伴在我们的应用程序代码中做到了这一点,并且它似乎有效。
我进行了 SO 和 Google 狂欢,试图向他解释不,Objective-C 类别只能用于添加方法,而不是属性。我发现了以下问题:
- Setting New Property In Category Interface Implementation(查看接受的答案)
- Can I add a property for a method not in my category?
但后来我在 Apple 的网站上找到了 this link,其中包含以下关于 @property 声明的内容:
属性声明以 关键字@property。 @property 可以 出现在方法的任何地方 声明列表中找到 @interface 类。 @property 可以 也出现在声明中 协议或类别。 (强调)
我知道这行不通:
@interface MyClass ()
NSInteger foobar;
- (void) someCategorizedMethod;
@end
但这编译:
@interface MyClass ()
@property NSInteger foobar;
- (void) someCategorizedMethod;
@end
我的问题是 (a) 这里的最佳做法是什么? (b) 这对 Objective-C 2.0 来说是新事物吗?不是使用“真正的”iVar,而是简单地在幕后使用关联存储来完成这项工作?
【问题讨论】:
标签: objective-c properties categories