NSNotificationCenter传递Block作为参数

- (void)touchesBegan:(NSSet<UITouch *> *)touches
           withEvent:(UIEvent *)event {
    void(^aBlock)(BOOL isTest);
    aBlock = ^(BOOL isTest) {
        NSLog(@"isTest == %i",isTest);
    };
    [[NSNotificationCenter defaultCenter] postNotificationName:@"nTest"
                                                        object:nil
                                                      userInfo:@{@"block":aBlock}];
}
- (void)viewDidLoad {
    [super viewDidLoad];    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(test:)
                                                 name:@"nTest" object:nil];
}

- (void)test:(NSNotification *)noti {
    void (^aBlock)(BOOL isTest) = noti.userInfo[@"block"];
    aBlock(YES);
}
打印结果
demo[68899:1075016] isTest == 1

我对传递Block作为参数,是这样理解的:
假设:C 需要根据 A 的某些参数值,做一些事情;但是 AC 并没有直接关系,故而,我们可以使用这种方式,做到特定值的传递。

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

推荐阅读更多精彩内容