Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About naming the instance variable in Objective C

Tags:

objective-c

Sometimes we may explicitly specify the name of an instance variable in the synthesize statement, e.g.,

In SomeViewController.h,

//....
@property (nonatomic, retain) NSObject *variable;
//....

In SomeViewController.m,

//....
@synthesize variable = _variable;
//....

But why bother making this extra effort if the instance variable will be implicitly named as _variable even if we simply put it as:

@synthesize variable;

in the SomeViewController.m.

Can anyone share some idea on why it is necessary? Thank you :D

like image 461
George Avatar asked Dec 04 '25 07:12

George


1 Answers

Just to avoid confusion (see comments): Using the = _variable part of the @synthesize is not required, nor is the @synthesize itself required any more.

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.

like image 127
Hermann Klecker Avatar answered Dec 07 '25 10:12

Hermann Klecker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!