I’m a bit confused when it comes to synthesize properties.
Lets say that I have this property in my *.h file.
@property (nonatomic, retain) NSString *aString;
And in my *.m file I synthesize it.
@synthesize aString;
I know that the compiler will generate setters and getters when Im using synthesize. But how does these setters and getters look like?
And when I shall give aString a value, which ways are correct?
self.aString = @"My New String"; // This will use the setter?
aString = @"My new String"; //This will not use the setter and retain the string, right?
aString = [@"My new string" retain]; //This will not use the setter, but it will retain the string ?
[self setAString:@"My new string"]; //This will also use the setter?
Thanks in advance!
When you do:
…followed by:
…your class gets three basic things:
aStringthat you can reference directly within your class.- (NSString*) aString;that returns the instance variable.- (void) setAString: (NSString*) value;that retains the parameter that is passed in and assigns it to the instance variable (and releases any previously retained value, if one exists);Implementation-wise, these generated methods and fields might look like:
So to answer the rest of your questions:
As for which are correct, they all are, depending upon what you want and assuming that you understand how the behavior differs between using each one, particularly with respect to releasing/retaining property values. For instance, this code will leak memory:
…and this equivalent code will not: