Block、协议、通知

2016-09-21  本文已影响30人  Dove_Q

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

    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

{
    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)后面代码的执行

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");
    sleep(3);
}
上一篇 下一篇

猜你喜欢

热点阅读