I’m not familiar with the program language which has both property and instance variable.
So I don’t know good ways to use property and instance variable.
Now I use only properties in my Objective-C code and I don’t use any instance variables.
Do I need to use instance variable?
Or using only property is the best practice for Objective-C?
@interface ViewController : UIViewController
{
// instance variable
@public
int a;
}
// property
@property(nonatomic, strong) NSString *b;
@end
Use properties everywhere. Don’t even declare instance variables, but synthesize them like this:
@synthesize myProperty = _myPropertyin order to differentiate them from property names. Properties are good way to cope with memory management as well. The only place you must use the synthesized instance variable is in thedeallocmethod.The advantages of the properties are a lot:
– The accessor methods define how will you get and set the value of your instance variable.
– You can customize the accessor methods (for example to lazy instantiate an ivar or do something when a setting a new value like
setNeedsDisplay.– You don’t cope with memory management when setting a new value – the setter takes care for releasing/retaining (depending how have you declared the property –
retain/copy/assign/strong.– Some multithreading stuff with the
atomic/nonatomicattributes– You can take advantage of the
KVO, when using properties– And least, but not last – don’t worry about performance issues if you have concernes that every time a getter or a setter is called…