【问题标题】:Declare instance variable nonproperty and property same name [duplicate]声明实例变量非属性和属性同名[重复]
【发布时间】:2013-09-17 15:06:53
【问题描述】:

为什么在许多片段代码中声明实例变量之类的以及为了什么?财产和非财产有什么不同

#import <Foundation/Foundation.h>

@interface class1:NSObject

{
   NSMutableString *currentData;
}
@property (nonatomic, retain) NSMutableString * currentData;

【问题讨论】:

  • 那是旧的。没有人应该再这样做了。只需申报财产。不再需要同时声明相应的 ivar。

标签: objective-c


【解决方案1】:

您看到的是“旧代码”...但有时您仍需要支持旧版本(例如 10.5)。

属性只是一对 getter 和 setter(嗯.. 它取决于您选择的属性:例如 readonly 将只生成一个 getter)。 但是属性操作(因此它需要)一个实例变量。通常您在实现文件中看到的内容类似于

@implementation class1
@synthesize currentData = currentData;
@end

这意味着创建使用 currentData 作为变量的 getter 和 setter。

对于较新的版本,您无需创建实例变量,只需键入属性和综合语句即可。在最新的语言版本中,您甚至不需要 synthesize 语句。自动创建一个名为_propertyName(下划线+属性名称)的实例变量。

顺便说一句:有时您仍然需要制作自己的 getter 和/或 setter。适用经典命名约定(例如,- (void)setCurrentData: (NSMutableString*)newData; 用于 setter,- (NSMutableString*)currentData; 用于 getter),但属性规则与以前相同:如果您仅支持最新的操作系统,则只需编写 @property 语句并正确设置您的 getter 和 setter通过使用“下划线”变量...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-26
    • 2012-02-21
    • 2012-07-15
    • 2014-02-06
    • 1970-01-01
    • 2012-09-05
    • 2011-03-05
    • 1970-01-01
    相关资源
    最近更新 更多