I am trying to really understand some memory management issues. And found this question, which partially answers the question I have.
For example, In MyObject I have an instance variable declared as a property and is properly synthesized in the implementation file:
@interface MyObject : NSObject
...
ObjectA objA;
...
@property (nonatomic, retain) ObjectA *objA;
@end
At some arbitrary point, I instantiate objA. I know self.objA = _objA; calls the synthesized accessor. Which, logically, means self.objA = [[ObjectA alloc] init]; would lead to a memory leak, since the retain count would be one more than intended (I know checking the retain count directly is not an accurate way of checking how long an object is going to be in memory).
Does objA = [[ObjectA alloc] init; also call the setter, and possibly lead to a memory leak?
Assigning the result of an
alloc/initto the raw instance variable is perfectly acceptable and is recommended for setting instance variables in an initialization method. To avoid leaking memory when using the synthesized setters you can take two approaches.1. Autorelease
Going through setter of ‘retain’ property increments the retain count. The alloc/init also incremented the retain count but is balanced by the autorelease meaning that it will be decremented by 1 and the end of the current event loop.
2. Assign to temporary variable first