A 101 question
Let\'s say i\'m making database of cars and each car object is defined as:
#import
@interface Car:NSObject{
Google's Objective-C Style Guide covers this pretty well:
Setters taking an NSString, should always copy the string it accepts. Never just retain the string. This avoids the caller changing it under you without your knowledge. Don't assume that because you're accepting an NSString that it's not actually an NSMutableString.
Without retain
there is no guarantee the NSString*
you are setting name
with will live any longer than the assignment statement itself. By using the retain
property for the synthesized setter you're allowing it to tell the memory management system that there is at least one more object interested in keeping the NSString*
around.
For those who are looking for it, Apple's documentation on property attributes is here.
and don't forget to access it via
self.name = something;
because
name = something;
will not care about the generated setter/getter methods but instead assign the value directly.
After reading so many Articles, SO posts and made demo apps to check Variable property attributes, I decided to put all the attributes information together
so below is the detailed article link where you can find above mentioned all attributes, that will defiantly help you. Many thanks to all the people who give best answers here!!
Variable property attributes or Modifiers in iOS
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
Would it be unfortunate if your class got this string object and it then disappeared out from under it? You know, like the second time your class mentions that object, it's been dealloc'ed by another object?
That's why you want to use the retain
setter semantics.