Game Development Reference
In-Depth Information
of assigning directly to an ivar, always assign to the property or run the property setter
method instead.
The next code fragment of Listing 5-8 is reprinted in Listing 5-9 to allow you to focus on
just the code discussed next.
Listing 5-9 . Creating a triggers NSPointerArray and assigning self to it
NSPointerArray* triggers = [triggerArrays
objectForKey:_name];
if (triggers == nil)
{
triggers = [NSPointerArray weakObjectsPointerArray];
[triggerArrays setObject:triggers forKey:_name];
}
[triggers addPointer:(void*)self];
In the first line, an NSPointerArray is obtained by looking up the object using the
trigger's _name in the triggerArrays . Initially, there will be no such object, result-
ing in triggers being nil . If that is the case, the if block will create an NSPoint-
erArray and assign it to triggers , as well as storing it in the triggerArrays dic-
tionary using the trigger's _name as the key.
The curious part is definitely the NSPointerArray . It sounds like a regular NSArray
or NSMutableArray , but it's actually not a subclass of either. It does behave much like
a trimmed-down variant of NSMutableArray , though. And its specialty is storing
pointer references and allowing you to store zeroing weak references to objects—meaning
the triggers array does not retain the trigger nodes added to it. If a trigger node stored
in the triggers array deallocates, the Objective-C runtime will automatically set the
corresponding pointer to nil in the array rather than leaving a dangling pointer (which,
when used, will cause crashes or bugs). The weakObjectsPointerArray initializer
configures the array to behave this way.
But why? Consider that both the trigger and target nodes could be removed from the node
hierarchy at any given point in time, whether they have been triggered or not. Trigger
nodes should not be kept from deallocating simply because you maintain a list of triggers
in a global array. Hence, storing them weakly (not retaining) in an NSPointerArray
allows triggers that are removed from the node hierarchy to deallocate.
Search WWH ::




Custom Search