美文网首页
简单回顾BLOCK,代理,和单例

简单回顾BLOCK,代理,和单例

作者: 遮住眼睛的草纸 | 来源:发表于2018-04-25 19:22 被阅读0次

    一、block按钮回调

    .h文件

    @class KLcustomBtn;
    
    typedef void (^Myblock)(KLcustomBtn *btn);//定义一个block类
    
    @property (nonatomic, strong) MyblockfirstBlock;
    
    +(instancetype)createAnewButton;
    

    .m文件

    //重写init方法,目的就是使得在按钮被初始化的时候就已经添加监听)addActionToButton方法
    
    -(instancetype)initWithFrame:(CGRect)frame{
    
    if (self=[super initWithFrame:frame]) {
    
        [self addTarget:self action:@selector(addActionToButton:) forControlEvents:UIControlEventTouchUpInside];
    
    }
    
    return self;
    
    }
    
    -(void)addActionToButton:(KLcustomBtn *)btn{
    
    if (_block!=nil) {
    
    _block(btn);
    
    }
    
    }
    
    +(instancetype)createAnewButton{
    
    returnreturn [KLcustomBtn buttonWithType:UIButtonTypeCustom];
    
    }
    

    调用的时候

    KLcustomBtn *btn =[KLcustomBtn createAnewButton];
    
    btn.block =^(KLcustomBtn *btn){
    
    //代码
    
    };
    

    同样适用于传递参数

    二、代理协议

    .h文件

    @protocol customBtnDelegate
    
    @optional
    
    -(void)pleaseObeydelegate:(KLcustomBtn *)btn;
    
    @end
    
    @interface KLcustomBtn : UIButton
    
    @property (nonatomic, weak) id delegate;
    
    @end
    

    .m文件

    //如果btn想告诉别的控制器一些事情,就在那个方法中加入
    
    if ([self.delegate respondsToSelector:@selector(pleaseObeydelegate:)]) {
    
    [self.delegate pleaseObeydelegate:self];
    
    }
    
    //在目标控制器中的.m文件中遵守协议
    
    KLcustomBtn *btn =[[KLcustomBtn alloc]init];
    
    btn.delegate =self;
    
    //再实现代理方法
    
    -(void)pleaseObeydelegate:(KLcustomBtn *)btn{
    
    NSLog(@“—————————————”);
    
    }
    

    三、GCD单例

    利用线程进行最简单的单例创建

    .h文件提供这样一个方法,以创建一个Button为例

    +(instancetype)shareCustomBtn;
    

    .m文件中这样来写

    1.定义全局静态static id instance

    2.重写allocWithZone方法

    +(instancetype)allocWithZone:(struct _NSZone *)zone{
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
    
    instance =[super allocWithZone:zone];//保证只执行一次
    
    });
    
    return instance;
    
    }
    

    3.实现方法

    +(instancetype)shareCustomBtn{
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
    
    instance =[[self alloc] init];
    
    });
    
    return instance;
    
    }
    

    最后调用这个对象,创建出来的就是指向同一内存地址的对象了。

    相关文章

      网友评论

          本文标题:简单回顾BLOCK,代理,和单例

          本文链接:https://www.haomeiwen.com/subject/zlmylftx.html