p. 178 - Why are you using allocWithZone instead of alloc?


I’d like an answer to this as well. Furthermore, what is the point of calling allocWithZone:NULL ?


The method alloc is just a dummy method. It’s implementation looks like this:

+ (id)alloc
      return [self allocWithZone:nil];

allocWithZone: will call the C function, NSAllocateObject. This function is where memory is actually allocated.

So, the goal of this singleton class is to prevent anyone from creating another instance of the class. If we were to override alloc, it would prevent the following:

id newInstance = [[SomeClass alloc] init];

However, this still leaves the possibility of doing this:

id newInstance = [[SomeClass allocWithZone:nil] init];

So, we’re preventing that from happening. If someone uses alloc, it calls our allocWithZone:. If someone uses allocWithZone:, it predictably calls our allocWithZone:, too. Another programmer can’t “jump” our alloc override because of this.


When I run Analyze I get the following message for the following method:

Object with +0 retain counts returned to caller where a +1 (owning) retain count is expected

// Here we prevent the creation of addiitonal instances

  • (id)allocWithZone:(NSZone *)zone
    return [self defaultStore];

I read the author’s description of this method on page 178 and 179 and don’t understand it completely. However, I suspect I can just ignore this warning.
I’m I correct? I don’t need a more detailed explanation at this point, just a yes (for "Don’t worry about it) or a no (for "You’d better resolve this warning, buddy) answer.


Right, you don’t have to worry about it. The analyzer is smart to pick it up, but in this case, this is the desired effect.


Thanks for your reply.
Paul Slapikas (aka PapaCat)


What the OP brought up got me thinking about any possible memory management issues with PossessionStore. Since a call to +allocWithZone was made in the +defaultStore method, this means PossessionStore is responsible for the instance. How would one go about managing memory for this singleton?

Thanx in advance!


What I don’t understand is why using allocWithZone would “jump an alloc override”?


What I don’t understand is why using allocWithZone would “jump an alloc override”?[/quote]

If we override alloc instead of allocWithZone a programmer using our class could still call alloc with zone to bypass our changes.