When you @synthesize an object type property in objective c, the compiler will generate two hidden methods for that instance variable. Thus when you refer myObject.myString
, not only the pointer of _myString will be returned, but the generated - (NSString*) myString
method will be called. Similarly if you assign something to the property: myObject.myString = @"foo";
it will be compiled to [myObject setMyString:@"foo"];
.
What is in - (NSString*) myString
and - (void) setMyString:(NSString*) theString
depends on the keywords you specify when declaring the property. The most common is assign
that simple assigns the pointer you give:
- (void) setMyString:(NSString*) theString
{
_myString = theString;
}
- (NSString*) myString
{
return _myString;
}
This makes not too much difference from declaring _myString a public variable, but it is more explicit way to say that this variable can be directly accessed from outside.
In turn, retain
generates similar setter method (getter method will be the same):
- (void) setMyString:(NSString*) theString
{
[theString retain];
[_myString release];
_myString = theString;
}
You can see that this takes care of the memory management of the object you passed into the property. In other words you can be sure that the object will be not released until you have it in your property, thus you don't have to retain
it manually when you take its ownership. This makes much more convenient to write code that manages the memory without leaks. Note, in the dealloc you still have to apply nil to your property in order to release the last object it stored.
Another category of properties when their data does not come from instance variables but from some other data source like a database. The auto-generated properties of the Managed Objects of Core Data for example work so.
At last, you can also define your own getters and setters. A good idea for example to write a property wrapper around some frequently used NSUserDefaults
settings, that will facilitate its access:
@interface Bar
@property (nonatomic, assign) NSString* foo;
@end
@implementation Bar
- (void) setFoo:(NSString *)theFoo
{
[[NSUserDefaults standardUserDefaults] setObject:theFoo
forKey:@"settings.foo"];
}
- (NSString*) foo
{
return [[NSUserDefaults standardUserDefaults]
stringForKey:@"settings.foo"];
}
@end
myBar.foo = @"foobar"; // automatically persisted between application runs
Read these also: Advanced memory management and Declared properties in objective C