Graphics Programs Reference
In-Depth Information
loc
in
BNRItemStore
so that it does not create a new instance but returns the existing
instance instead.
However, there is a problem with this approach:
alloc
is a dummy method. It just calls
allocWithZone:
, which then calls the C function
NSAllocateObject
, which does
the actual memory allocation (
Figure 9.7
).
Figure 9.7 Default allocation chain
Thus, a knowledgeable programmer could still create an instance of
BNRItemStore
via
allocWithZone:
, which would bypass our sneaky
alloc
trap. To prevent this pos-
sibility, override
allocWithZone:
in
BNRItemStore.m
to return the single
BNRItemStore
instance.
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}
Now if
sharedStore
were to send
alloc
or
allocWithZone:
to
BNRItemStore
, then the method would call
BNRItemStore
's implementation of
allocWithZone:
. That implementation just calls
sharedStore
, which would then