I have seen sample source code around that uses different ways of releasing/dealloc’ing objects, so I was wondering which way is deemed the ‘best’ one. A few options on -dealloc:
1) Release objects
- (void)dealloc { [obj1 release]; [obj2 release]; [super dealloc]; }
2) Set objects to nil
- (void)dealloc { self.obj1 = nil; self.obj2 = nil; [super dealloc]; }
3) De-allocate objects directly
- (void)dealloc { [obj1 dealloc]; [obj2 dealloc]; [super dealloc]; }
Which way is the best one? Pros and cons for each?
Method 1 is the only recommended method. It’s also good practice to set them to nil AFTER you’ve released them.
Method 2 only works for properties that manage their own object/value retaining, so it’s not universally applicable. And if you implement your own setter method that performs other actions when the property changes, you may get undesired side effects by calling it in [dealloc].
Method 3 violates the reference-counting principle because it will deallocate the objects even if something else has a [retain] hold on them, so when the other objects access them next, your program will crash. You’re never supposed to call [dealloc] directly — let the runtime call it when the last owner calls [release].