关于在Objective C中命名实例变量

Geo*_*rge 2 objective-c

有时我们可以在synthesize语句中明确指定实例变量的名称,例如,

SomeViewController.h,

//....
@property (nonatomic, retain) NSObject *variable;
//....
Run Code Online (Sandbox Code Playgroud)

SomeViewController.m,

//....
@synthesize variable = _variable;
//....
Run Code Online (Sandbox Code Playgroud)

但是,如果将实例变量隐式命名为_variable即使我们简单地将它作为:

@synthesize variable;
Run Code Online (Sandbox Code Playgroud)

SomeViewController.m.

任何人都可以分享为什么有必要吗?谢谢你:D

Her*_*ker 8

只是为了避免混淆(见注释):使用= _variable部分@synthesize不是必需的,也不再需要@synthesize它本身.

This effort is only requied, when you want to link the property to a specific instance variable. With earlier Objective-C versions this part of the statement was required to set the name to something different from the property name, so when you want to call the iVar _variable and the property variable. The default would be variable (unlike your question). Without that = something ivar and property have the same name.

BTW, there is nothing wrong with using the same name for both. But having different names, a leading _ would do, makes it more clear to the programmer whether he/she accesses the ivar directly or though the accessor methods. Sometimes this is of vast importance, especially when not using ARC. Therefore it helps avoiding errors.

With current Objective-C, however, you could omit the @synthesize statement at all and go with the defaults in that case. The default automatically synthesized instance variable name would have a leading _ so _variable in your example.

  • "使用早期的Objective-C版本**需要**将名称设置为与属性名称不同的名称"?在我出生之前? (2认同)
  • @congliu,坦率地说,我不太确定它何时被引入Objective-C,`@ synthesize`是可选的.我使用Obj-C 1992/93然后它不是可选的,除非你自己提供了getter和setter以及所有内存管理开销等.现在我再次使用它,因为2或3年(强度不同)从我的观点来看,自动合成可以节省一些时间和精力. (2认同)