Public/Private
You can declare your iVars as in the @interface file to be readonly, but then re-declare them in a category so that your class can change them. Here's a quick intro to Categories.
An example:
//MyClass.h
@interface MyClass : NSObject {
NSString *name;
}
@property (readonly) NSString *name;
@end
And in the implementation file you can redeclare this:
//MyClass.m
@interface MyClass () //declare the class extension
@property (readwrite, copy) NSString *name; //redeclare the property
@end
@implementation MyClass
@synthesize name;
@end
Now, the name
property is readonly external to the class, but can be changed by the class through property syntax or setter/getter syntax.
Really private iVars
If you want to keep iVars really private and only access them directly without going through @property syntax you can declare them with the @private
keyword. But then you say "Ah, but they can always get the value outside the class using KVC methods such as setValueForKey:
" In which case take a look at the NSKeyValueCoding protocol class method + (BOOL)accessInstanceVariablesDirectly
which stops this.
IBOutlets as properties
The recommended way is to use @property and @synthesize. For Mac OS X, you can just declare them as readonly properties. For example:
//MyClass.h
@interface MyClass : NSObject {
NSView *myView;
}
@property (readonly) IBOutlet NSView *myView;
@end
//MyClass.m
@implementation MyClass
@synthesize myView;
@end