Iphone 有人能解释推送通知代码中的对象部分吗?
我遇到了一段代码,该代码正在注册通知:Iphone 有人能解释推送通知代码中的对象部分吗?,iphone,objective-c,ios,Iphone,Objective C,Ios,我遇到了一段代码,该代码正在注册通知: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(someStuff:) name:@"someStuff"
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someStuff:)
name:@"someStuff"
object:nil];
然后用以下方法触发它:
[[NSNotificationCenter defaultCenter] postNotificationName:@"someStuff" object:self];
为什么一个对象设置为nil,另一个对象设置为self?那有什么用 首先考虑第二种情况,当您发布通知时,您会指出哪个对象是该通知的发送者。通常这是“self”,但您可以代表其他对象发布通知 另一方面,当您注册以观察通知时,可以指定您只希望观察由特定对象发布的通知。因此,您可以说“我想观察‘酷新数据’通知,但仅当此特定对象发布通知时,才可以。如果其他对象说有‘酷新数据’,我不感兴趣。” 如果在注册观察者时将nil作为“object”参数传递,则表示您不在乎谁发布此通知,您希望为任何发送者触发选择器(或块)。因此,如果有人发布“酷新数据”,我想知道
顺便说一句,这些不是“推送通知”。这是一个不同的功能/API。引用apple docs。。第一个对象是 通知发送者
The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the
The object posting the notification.
观察员
If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.
第二个是
通知发送者
The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the
The object posting the notification.
所以在第二种情况下,这告诉我们谁在发送这个通知,这就是那个类本身