In a header file such as this, when would an instance variable be used and when would a property be used?
Do they have to have the same name?
#import <UIKit/UIKit.h>
@class BlueViewController;
@class YellowViewController;
@interface SwitchViewController : UIViewController {
YellowViewController *yellowViewController;
BlueViewController *blueViewController;
}
@property (retain, nonatomic) YellowViewController *yellowViewController;
@property (retain, nonatomic) BlueViewController *blueViewController;
@end
A
@propertydeclaration simply creates accessor methods for an ivar. So properties don’t really have names, only the accessor methods do; and these don’t have to have the same name as the ivar. In fact, they don’t even have to have a corresponding ivar.You can change the names of the methods using the
getterandsetterdecorators like this:Now, as I said, a
@propertydeclaration simply creates accessor methods for an ivar. So you use properties when you want accessor methods. Here are a few reasons why you might want accessor methods:Encapsulation (a property might be advertised as a different type than the ivar, or might not even have an ivar)
Related state changes (change another ivar or invoke a method when an ivar is modified)
You can use the
retaindecorator and@synthesizethe property to get much simpler memory managementYou can use
atomicdecorator (or simply not use thenonatomicdecorator, since properties are atomic by default) to create atomic propertiesHere’s an example to demonstrate points 1 and 2: