iOS开发 ☞ NSNotification

来源:互联网 发布:知乎 ipad笔记 编辑:程序博客网 时间:2024/05/17 07:25

一、多次注册通知

- (void)viewDidLoad {    [super viewDidLoad];    UIButton *testBtn = [UIButton buttonWithType:UIButtonTypeCustom];    testBtn.frame = CGRectMake( 100, 100, 100, 100);    testBtn.backgroundColor = [UIColor orangeColor];    [testBtn addTarget:self action:@selector(postNoti) forControlEvents:UIControlEventTouchUpInside];    [self.view addSubview:testBtn];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"aaaa" object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"aaaa" object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"aaaa" object:nil];    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"aaaa" object:nil];}- (void)test {    NSLog(@"tttttt");}- (void)postNoti {    [[NSNotificationCenter defaultCenter] postNotificationName:@"aaaa" object:nil];}

结果如下:
这里写图片描述
结论,在开发中,要根据具体情况移除通知,避免叠加

二、关于通知的一些常用API
通知中心添加观察者

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"aaaa" object:nil];

通知中心发送通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"aaaa" object:nil];

具体说说观察者的移除(可以从KVO的角度理解)

移除观察者对aaaa通知的监听,这个方法的使用需要谨慎而行,因为如果观察者没有监听aaaa通知就会崩溃,从KVO的角度理解,就是移除对通知中心aaaa这个属性的监听,当然,self对象还可以监听通知中心别的属性[[NSNotificationCenter defaultCenter] removeObserver:self name:@"aaaa" object:nil];这个方法是通知中心移除self对象的监听,从KVO角度理解,self将失去对通知中心所有属性的监听。如果self对象没有监听通知中心的任何消息也不会导致崩溃.[[NSNotificationCenter defaultCenter] removeObserver:self];
1 0
原创粉丝点击