1
我在找一個有「事件列表」的類,類似於UIButton的工作方式,您可以在其中添加多個目標和選擇器。UIKit中是否有基類/工具類,內置事件處理?
編寫一個很容易,但如果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
不完全是我所希望的答案。我決定走下自定義路徑,並推出我自己的派發事件的基類。 – Brian 2012-07-24 18:52:41