- 
                Notifications
    You must be signed in to change notification settings 
- Fork 6
When to release and when to autorelease
        Nat! edited this page Apr 7, 2017 
        ·
        2 revisions
      
    The general rule for when to call -release or -autorelease are simple:
- You always -autorelease, unless you are writing-dealloc
- In -deallocyou should always use-release.
- You may -releasein-initif you are returning nil
So you also
-autoreleasein-finalize
It's not bad to -autorelease in -dealloc it is just wasteful.
The advantage of this code:
obj = [Foo new];
[container addObject:obj];
[obj release];
vs.
obj = [Foo instantiate];
[container addObject:obj];
are, that a -release can be a bit faster than -autorelease.
If you are writing a container, which could hold a large
quantity of objects, it may pay off.
A problem is that you can all to easily steer into a situation like this:
+ (id) newFooWithContainer:(NSMutableArray *) array
{
   id   obj;
   obj = [Foo new];
   [array addObject:obj];
   [obj release];
   ...
   return( obj);
}
What happens when array is nil ?