views:

297

answers:

2

In Apple's NSObject documentation, NSZoneFree is called in the - (void)dealloc example code:

- (void)dealloc {
    [companion release];
    NSZoneFree(private, [self zone])
    [super dealloc];
}

You can find it in context over here.

I never had the notion that I should be calling NSZoneFree in my own NSObject subclasses (or what NS_WhateverClass_ subclasses) and can't find anything conclusive on the topic anywhere in the docs.

All I can find about using NSZoneFree is a brief mention in the Memory Management Programming Guide, and an explanation of the function in the Foundation Functions Reference, but none of these docs make it clear to me whether I should worry about it in the context of a dealloc method.

Can anybody clarify when I should put an NSZoneFree call in my own classes' dealloc implementations?

Edit: Thanks for your replies, it's clearer to me now :) — Dirk

+1  A: 

According to the Foundation Reference:

Returns memory to the zone from which it was allocated. The standard C function free does the same, but spends time finding which zone the memory belongs to.

So, you basically use NSZoneFree(), instead of free(), when cleaing up malloc'd and calloc'd memory. You generally don't need to call it, however.

Ben Gottlieb
+2  A: 

NSZoneFree() balances out a call to NSZoneMalloc(), just like -release balances a call to -alloc or -copy and CFRelease() balances a call to CFRetain() or CF*Create*() or, for that matter, free() balances a call to malloc() or calloc().

Given the allocator(s) that the C library uses on Mac OS X, much of this is academic, but best practices say that you release your hold on memory the same way you got it, and in the case of that class, the instance variable private had previously been allocated with NSZoneMalloc().

Jim Puls