Reputation: 18487
Quick question: I use lots of NSObject derived classes and am wondering how to properly cleanup class properties that may own instances of other classes (in the snippet below this is an array of custom class instances). Is my usage of new
and finalize
below correct?
My understanding is that new
is a convenience method that calls both alloc and init, and finalize
gets called before dealloc
- at least this is what I have gleaned from reading the docs. Do I have this right?
Thanks for any tips/best practices, etc!
- (id)new {
waffleArray = [[NSMutableArray alloc] initWithCapacity:kCellCount];
for (int i = 0; i < kCellCount; i++) {
WaffleCell * cell = [WaffleCell new];
[waffleArray addObject:cell];
}
return self;
}
// clean up
- (void)finalize {
[waffleArray removeAllObjects];
waffleArray = nil;
[super finalize];
}
Upvotes: 0
Views: 1757
Reputation: 34912
new
on NSObject
is a class method, not an instance method as you have it. Also I don't really see why you'd overload new
. It would be more common to overload init
so something like this:
- (id)init {
if ((self = [super init])) {
waffleArray = [[NSMutableArray alloc] initWithCapacity:kCellCount];
for (int i = 0; i < kCellCount; i++) {
WaffleCell * cell = [WaffleCell new];
[waffleArray addObject:cell];
}
}
return self;
}
As for finalize
, you really don't need to do that. This is what Apple says about it:
The garbage collector invokes this method on the receiver before disposing of the memory it uses. When garbage collection is enabled, this method is invoked instead of dealloc.
With ARC enabled you wouldn't need to do anything and since the garbage collector will not be running anyway, finalize
won't get called anyway. ARC will automatically generate code which will release
waffleArray
in dealloc
for you, which is enough for proper memory management in this case because waffleArray
's retain count will then drop to 0, be deallocated itself which will go and release the objects in the array.
Upvotes: 1