iOS里防止按钮被多次点击的办法

原理:利用局部变量生存期局限在当前函数或者当前代码块的原理,实现C++里AutoLock的概念,其实也就是智能指针的概念.

利用局部变量在创建时执行按钮的setEnable为NO,在函数结束,且无block的情况下setEnable为YES.如果有block,需要调下blockIt函数,其实里面啥都不干,就是为了让LLVM知道这个变量要在block结束后才释放.

头文件

@interface D1AutoDisableButton : NSObject
{
    UIButton* sender;
}
//调用接口,声明一个临时变量,注意不能是全局的或者self成员级的,如果要跨函数调用,请将其作为参数传递
+(id)objectWithButton:(UIButton*)obj;
//在block里随便做点什么,不然变量就在block执行前就释放了.
-(void)blockIt;
@end

 实现

@implementation D1AutoDisableButton

-(id)init
{
    [super doesNotRecognizeSelector:_cmd];
    return nil;
}
+(id)objectWithButton:(UIButton*)obj
{
    D1AutoDisableButton* lockObj = [[D1AutoDisableButton alloc]initWithParam:obj];
    return lockObj;
}
-(id)initWithParam:(UIButton*)obj
{
    sender = obj;
    [sender setEnabled:NO];
//    NSLog(@"auto disable:%x",sender);
    return self;
}
-(void)dealloc
{
    [sender setEnabled:YES];
    //NSLog(@"auto enable:%x",sender);
}
-(void)blockIt
{
    //NSLog(@"block call it");
}
@end

 使用了ARC

原文地址:https://www.cnblogs.com/decwang/p/4892798.html