- (void)addTarget:(id)target action:(SEL)action forControlEvents:(ASControlNodeEvent)controlEventMask
{
NSParameterAssert(action);
NSParameterAssert(controlEventMask != 0);
// Convert nil to [NSNull null] so that it can be used as a key for NSMapTable.
if (!target)
target = [NSNull null];
// Enumerate the events in the mask, adding the target-action pair for each control event included in controlEventMask
_ASEnumerateControlEventsIncludedInMaskWithBlock(controlEventMask, ^
(ASControlNodeEvent controlEvent)
{
// Do we already have an event table for this control event?
id<NSCopying> eventKey = _ASControlNodeEventKeyForControlEvent(controlEvent);
NSMapTable *eventDispatchTable = [_controlEventDispatchTable objectForKey:eventKey];
// Create it if necessary.
if (!eventDispatchTable)
{
// Create the dispatch table for this event.
eventDispatchTable = [NSMapTable weakToStrongObjectsMapTable];
[_controlEventDispatchTable setObject:eventDispatchTable forKey:eventKey];
}
// Have we seen this target before for this event?
NSMutableArray *targetActions = [eventDispatchTable objectForKey:target];
if (!targetActions)
{
// Nope. Create an actions array for it.
targetActions = [[NSMutableArray alloc] initWithCapacity:kASControlNodeActionDispatchTableInitialCapacity]; // enough to handle common types without re-hashing the dictionary when adding entries.
[eventDispatchTable setObject:targetActions forKey:target];
}
// Add the action message.
// Note that bizarrely enough UIControl (at least according to the docs) supports duplicate target-action pairs for a particular control event, so we replicate that behavior.
[targetActions addObject:NSStringFromSelector(action)];
});
self.userInteractionEnabled = YES;
}
下面这个方法是C 风格的方法,为什么要这么写呢?
12345678910
void _ASEnumerateControlEventsIncludedInMaskWithBlock(ASControlNodeEvent mask, void (^block)(ASControlNodeEvent anEvent))
{
// Start with our first event (touch down) and work our way up to the last event (touch cancel)
for (ASControlNodeEvent thisEvent = ASControlNodeEventTouchDown; thisEvent <= ASControlNodeEventTouchCancel; thisEvent <<= 1)
{
// If it's included in the mask, invoke the block.
if ((mask & thisEvent) == thisEvent)
block(thisEvent);
}
}