Search code examples
objective-cmemory-managementretain

Clarification on when to release pointers after allocating


In my last question (here), I had an issue where I was getting an EXC_BAD_ACCESS because I was releasing the variable I had just allocated:

NSMutableArray* s = [[NSMutableArray alloc] init];
stack = s;
[s release];

should have been

NSMutableArray* s = [[NSMutableArray alloc] init];
stack = s;

However, stack is a retained property of my class. It's declared like so:

@interface StateStack ()
@property (nonatomic, retain) NSMutableArray* stack;
@end

I was under the impression that when you assign a 'retain' variable, it automatically increments the retainCount of the object. So you are supposed to start by releasing your pointer (as here).

Why are these two cases different? Thanks!


Solution

  • There is no such thing as a "retain variable". It's a retain property — meaning the setter method behind the property retains the new value and releases the old one. But assigning to a variable just assigns. In fact, the reason people generally recommend assigning directly to the instance variable in init is specifically so that it doesn't go through the setter, because the setter could conceivably have side effects you don't want in init (when your object isn't fully constructed yet).

    Note: I'm talking about normal memory-management rules here. This is all different if you're using ARC. But I assume you would have mentioned if you were.