What difference does it make in memory management to define a variable as a property? For instance:
@interface foo {
NSString *theStr;
}
@end
@implementation foo
- (void)bar {
NSLog(theStr);
}
@end
Versus:
@interface foo {
NSString *theStr;
}
@property(retain) NSString *theStr;
@end
@implementation foo
@synthesize theStr;
- (void)bar {
NSLog(theStr);
}
@end
It seems like the first is autoreleased or something similar, while the second is retained throughout the life of the class. Is that the case, or what is the difference?
If you define a variable just in the interface without defining it as a property (as in your first example) means that you’ll have to take care of everything related to memory management yourself. Assigning something to that variable will not retain it automatically, not will setting the variable to something else release the previous value.
Defining it as a property creates getter and setter methods under the hood. Most importantly, if you use it with the “retain” keyword, your setter method will retain the new value (and release the old one if there was one).
Note that the setter method will only be invoked if you use the dot notation, e.g.,
self.myStr = @"new string", or the method call, e.g.,[self setMyStr:@"new string"]. If you just callmyStr = @"new string"the setter method will not be called and you need to release the old value yourself and retain the new one.