3 ms·
3. When you type self.foo = bar, there is an implied retain. If you set a class variable without the "self," there is no implied retain. No no no no no... Tha
by kelnos 16y ago
3. When you type self.foo = bar, there is an implied retain. If you set a class variable without the "self," there is no implied retain.
No no no no no... That is absolutely incorrect. Only properties declared "retain" do that.
@property (nonatomic, assign) NSObject *foo; // doesn't retain
@property (nonatomic, copy) NSObject *bar; // doesn't retain
@property (nonatomic, retain) NSObject *baz; // *does* retain
(The 'nonatomic' isn't related to the retain/no-retain semantics, but most properties are declared nonatomic, as atomic properties have some locking overhead.)
On a side note, a discussion of iOS/Mac memory management isn't very useful if it doesn't talk about how autorelease pools work.
- andrewljohnson 16y agoYou are right, I will correct it. Also, hopefully this post is useful as is at least for beginners, though adding information on autorelease pools would be good for sure.
- rbritton 16y agoOn the topic of properties, I also find it helpful to define the property and variable to have different names (e.g., NSString _foo; for the variable and @property (nonatomic, copy) NSString foo; for the property). When mapped through @synthesize foo = _foo;, it avoids confusion about the memory management necessary for a particular value.
- zpasternack 16y agoThe same thing applies to "copy" properties. If you do "self.foo = bar;" when foo is a copy property, you have taken ownership of that object, and need to release it later (hopefully by doing "self.foo = nil;".
- kelnos 15y agoSimilar, but not the same, though yes, releasing it can be done in the same manner.