美文网首页
9.21 Block、协议、通知

9.21 Block、协议、通知

作者: jayck | 来源:发表于2016-09-22 18:37 被阅读15次

    Block

    注: 将时机放到自己成员函数内部,防止出现循环引用

    CustomView.h文件

    @interface CustomView : UIView
    - (void)demoFunc:(void(^)(void))handle;
    @end
    

    CustomView.m文件

    @interface CustomView (){
    void (^globalHandle)(void);
    }
    @end
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
      if(globalHandle){ 
      globalHandle(); 
    }
    }
    - (void)demoFunc:(void (^)(void))handle{ 
      globalHandle = handle;
    }
    

    ViewController.h文件

    CustomView *v = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    v.center = self.view.center; [self.view addSubview:v]; 
    v.backgroundColor = [UIColor redColor]; [v demoFunc:^{ 
    NSLog(@"hello world"); 
    }];
    

    协议

    Custom.h文件

    @protocol CustomViewDelegate <NSObject>
    @optional- (void)messageSend;
    @end@property(nonatomic,weak)id<CustomViewDelegate> delegate;
    

    Custom.m文件

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ 
    if([self.delegate respondsToSelector:@selector(messageSend)]){ 
    [self.delegate messageSend]; 
    }
    }
    

    ViewController.h文件

    { 
    CustomView *v = [[CustomView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)]; 
    v.center = self.view.center; 
    [self.view addSubview:v]; 
    v.backgroundColor = [UIColor redColor];
    v.delegate = self;
    }
    - (void)messageSend{ NSLog(@"hello world_delegate");
    }
    

    通知

    注: 通知一般用于一对多,当"1"里面的代码比较多的时候,会影响"2"后面代码的执行,key比较难管理。而且一旦某个过程慢了半拍,或者出现卡顿时,其他函数也会被影响。

    Custom.m文件

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"kClicked" object:nil]; 
    }//"2"
    

    ViewController

    { 
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notiHandle:) name:@"kClicked" object:nil];
    }
    - (void)notiHandle:(NSNotification*)noti{ 
    // "1" NSLog(@"hello world_noti");
    }
    

    相关文章

      网友评论

          本文标题:9.21 Block、协议、通知

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