美文网首页
关于 NSNotificationCenter 中的 objec

关于 NSNotificationCenter 中的 objec

作者: 杨晓晨 | 来源:发表于2017-12-01 14:47 被阅读0次

先看如下一段代码

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

在以前的习惯当中,使用通知往往会忽略上面 object 参数,一般大家都会传 nil,但是今天突然对这个 object 参数很好奇,如果传入这个参数会怎么样?于是我就写了上面的代码测试一下。下面是触发通知的操作

[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:@"2"];

接着是通知触发后的回调函数

- (void)test:(NSNotification *)no {
    NSInteger count = self.countLable.text.integerValue;
    self.countLable.text = [NSString stringWithFormat:@"%zu", ++count];
}

但是结果是触发通知后回调函数不回调,WTF? Why?但是我把添加通知和触发通知中的 object 参数改成一样的就可以了,所以这个 object 到底是个什么东东?又有什么作用呢,看一下水果的文档如下


image.png

anObject

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer. If you pass nil, the notification center doesn’t use a notification’s sender to decide >>whether to deliver it to the observer.

大致意思就是这个 object 参数是你想要接收的参数,当收到和这个参数一致的通知的时候参会触发回调函数的执行,如果和这个参数不一致则不会触发回调函数。那这样做有什么用呢?
如果我有一个需求,用户点击某个按钮十次才会触发某个事件,那么我就可以把这个参数设置为 @10,每次点击将发送的 object 加1,这样当点击的数量等于10的时候就可以自动触发回调事件而不需要写

相关文章

网友评论

      本文标题:关于 NSNotificationCenter 中的 objec

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