I had some discussion related to the use of properties and instance variables at work, therefore I would like to find a wiki answer for that. Now, I know there\'s no real pr
By using class extensions you can have private properties.
A class extension syntax is simple:
Inside the .m-file, that has the class, create a unnamed category:
.h
@interface OverlayViewController : UIViewController
- (IBAction)moreButtonClicked:(id)sender;
- (IBAction)cancelButtonClicked:(id)sender;
@end
.m
#import "OverlayViewController.h"
@interface OverlayViewController ()
@property(nonatomic) NSInteger amount;
@property(retain,nonatomic)NSArray *colors;
@end
@implementation OverlayViewController
@synthesize amount = amount_;
@synthesize colors = colors_;
//…
@end
Now you got all the aspects of properties for private members, without exposing them to public. There should be no overhead to synthesized properties to written getter/setters, as the compiler will create more or less the same at compile time.
Note that this code uses synthesized ivars. No ivar declaration in the header is needed.
There is a nice cocoawithlove article, about this approach.
You also ask why to use properties for private ivars. There are several good reasons:
Since LLVM 3 it is also possible, to declare ivars in class extensions
@interface OverlayViewController (){
NSInteger amount;
NSArray *colors;
}
@end
or even at the implementation block
@implementation OverlayViewController{
NSInteger amount;
NSArray *colors;
}
//…
@end
see "WWDC2011: Session 322 - Objective-C Advancements in Depth" (~03:00)