iPhone How-to:怎么清除控件的Target-Action

iPhone How-to:如何清除控件的Target-Action
iPhone中的Target-Action的作用和C++中的Callback以及C#中的EventHandler很相似,都是用于事件响应。继承自UIControl的控件都可以通过-(void)addTarget:action:forControlEvents的消息进行某些事件处理函数的注册,在不需要的时候还可以通过-(void)removeTarget:action:forControlEvents取消事件处理函数。不过应用开发中在添加时会逐个添加,但在清理时通常则是希望一次性清理干净。但-(void)removeTarget:action:forControlEvents需要传入指定target,因此只能清理指定target的处理函数,而不能清理全部。为此需要对UIControl进行相应的扩张,代码如下:

Category声明:
@interface UIControl (Additions)
- (void)removeAllTargets;
@end
 
Category实现:
@implementation UIControl (Additions)
- (void)removeAllTargets { 
        for (id target in [self allTargets]) { 
                [self removeTarget:target action:NULL forControlEvents:UIControlEventAllEvents]; 
        } 
}
@end


从代码中可以看出,本质上彻底清理所有target的处理函数也是通过逐个清理实现的,但由于提供了removeAllTargets,对外隐藏了实现细节,实际应用中就可以轻松搞定了。