Reputation: 138
When do you have to use @property
and @synthesize
in the iPhone SDK? And why use @property
and @synthesize
?
I was studying property, but I can't get a correct idea. What would some examples for illustrating this be?
Upvotes: 0
Views: 2387
Reputation: 18741
@property : you used it when you want to:
You can use some of the really useful generated code like nonatomic, atmoic, retain without writing any lines of code. You also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.
@property is really good for memory management, for example: retain.
How can you do retain without @property?
if (_variable != object) {
[_variable release];
_variable = nil;
_variable = [object retain];
}
How can you use it with @property?
self.variable = object;
When you are calling the above line, you actually call the setter like [self setVariable:object] and then the generated setter will do its job
Upvotes: 3
Reputation: 15853
@property (along with @synthesize) automatically generates set
and/or get
code. So the following code:
self.prop = @"some string";
is equivalent to
[self setProp: @"some string"];
Note also,
self.prop = @"some string";
is different from
prop = @"some string";
The latter sets the variable directly, whereas the former calls the method getProp
to set the variable prop
.
Upvotes: 2