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];
}
newonNSObjectis a class method, not an instance method as you have it. Also I don’t really see why you’d overloadnew. It would be more common to overloadinitso something like this:As for
finalize, you really don’t need to do that. This is what Apple says about it:With ARC enabled you wouldn’t need to do anything and since the garbage collector will not be running anyway,
finalizewon’t get called anyway. ARC will automatically generate code which willreleasewaffleArrayindeallocfor you, which is enough for proper memory management in this case becausewaffleArray‘s retain count will then drop to 0, be deallocated itself which will go and release the objects in the array.