Here is an example class which has a couple of instance variables, without using properties:
@interface TestClass : NSObject {
NSString *_someString;
int _someInt;
}
-(NSString *)someString;
-(void)setSomeString:(NSString *)newString;
-(int)someInt;
-(void)setSomeInt:(NSString *)newInt;
@end
@implementation TestClass
-(NSString *)someString {
return _someString;
}
-(void)setSomeString:(NSString *)newString {
_someString = newString;
}
-(int)someInt {
return _someInt;
}
-(void)setSomeInt:(int)newInt {
_someInt = newInt;
}
@end
This is quite a lot of boilerplate code to create a simple instance variable. You have to create the instance variable & create accessor methods which do nothing except set or return the instance variable. So with Objective-C 2.0, Apple introduced properties, which auto-generate some or all of the boilerplate code.
Here is the above class rewritten with properties:
@interface TestClass
@property NSString *someString;
@property int someInt;
@end
@implementation testClass
@end
A property is an instance variable paired with auto-generated getters and setters. For a property called someString
, the getter and setter are called someString
and setSomeString:
respectively. The name of the instance variable is, by default, the name of the property prefixed with an underscore (so the instance variable for someString
is called _someString
, but this can be overridden with an @synthesize
directive in the @implementation
section:
@synthesize someString=foo; //names the instance variable "foo"
@synthesize someString; //names it "someString"
@synthesize someString=_someString; //names it "_someString"; the default if
//there is no @synthesize directive
Properties can be accessed by calling the getters and setters:
[testObject setSomeString:@"Foo"];
NSLog(@"someInt is %d", [testObject someInt]);
They can also be accessed using dot notation:
testObject.someString = @"Foo";
NSLog(@"someInt is %d", testObject.someInt);