Block、协议、通知

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);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Block 注: 将时机放到自己成员函数内部,防止出现循环引用 CustomView.h文件 CustomView...
    jayck阅读 146评论 0 0
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,210评论 30 471
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,284评论 25 708
  • 禅与 Objective-C 编程艺术 (Zen and the Art of the Objective-C C...
    GrayLand阅读 1,645评论 1 10
  • Windows 7 系统。桌面上莫名多了一个IE图标,不是快捷方式。右键删除不管用。右键属性会打开IE设置。妹子的...
    KK7384阅读 454评论 0 1