我正在寻找一个具有类似于 UIButton 工作方式的“事件列表”的类,您可以在其中添加多个目标和选择器。
编写一个很容易,但如果 Apple 已经提供了解决方案,我宁愿使用它也不愿维护更多代码。
笔记:
这是一个非可视类,所以我真的不想使用任何 UI 特定的东西。
编辑:
我最终使用堆叠的 NSDictionary 实例滚动了我自己的基本事件调度程序类型类。
@implementation ControllerBase
@synthesize eventHandlers;
- (id) init
{
self = [super init];
if (self!=NULL)
{
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[self setEventHandlers: dict];
[dict release];
}
return self;
}
-(void) addTarget: (id) target action:(SEL) selector forEvent:(NSString*) eventName
{
NSString* selectorString = NSStringFromSelector(selector);
NSMutableDictionary* eventDictionary = [eventHandlers objectForKey:eventName];
if (eventDictionary==NULL)
{
eventDictionary = [[NSMutableDictionary alloc] init];
[eventHandlers setValue:eventDictionary forKey:eventName];
}
NSArray* array = [NSArray arrayWithObjects:selectorString,target, nil];
[eventDictionary setValue:array forKey: [target description]];
}
-(void) removeTarget: (id) target action:(SEL) selector forEvent:(NSString*) eventName;
{
NSMutableDictionary* eventDictionary = [eventHandlers objectForKey:eventName];
//must have already been removed
if (eventDictionary!=NULL)
{
//remove event
[eventDictionary removeObjectForKey:target];
//remove sub dictionary
if ([eventDictionary count]==0)
{
[eventHandlers removeObjectForKey:eventName];
[eventDictionary release];
}
}
}
-(void) fireEvent:(NSString *)eventName
{
NSMutableDictionary* eventDictionary = (NSMutableDictionary*) [eventHandlers objectForKey:eventName];
if (eventDictionary!=NULL)
{
for(id key in eventDictionary)
{
NSArray* eventPair= [eventDictionary valueForKey:key];
if (eventPair!=NULL)
{
NSString* selectorString = (NSString*)[eventPair objectAtIndex:0];
//remove colon at end
SEL selector = NSSelectorFromString ( [selectorString substringWithRange: NSMakeRange(0, [selectorString length]-1)] ) ;
id target = [eventPair objectAtIndex:1];
[target performSelector:selector];
}
}
}
}
-(void) dealloc
{
for(id key in eventHandlers)
{
NSMutableDictionary* eventDictionary = (NSMutableDictionary*) [eventHandlers objectForKey:key];
for(id key in eventDictionary)
{
[eventDictionary removeObjectForKey:key];
}
[eventDictionary release];
}
[eventHandlers release];
[super dealloc];
}
@end