Ios 移除观察者时是否未移除NSNotification观察者关闭?

Ios 移除观察者时是否未移除NSNotification观察者关闭?,ios,swift,Ios,Swift,我在视图控制器中有以下代码来注册我的一个自定义通知。到目前为止,我一直在使用选择器进行注册,但我想我会尝试使用闭包,然后注意到一些奇怪的事情 NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: "NotificationKey", object: nil) NSNotificationCenter.defaultCenter().addObserverFor

我在视图控制器中有以下代码来注册我的一个自定义通知。到目前为止,我一直在使用选择器进行注册,但我想我会尝试使用闭包,然后注意到一些奇怪的事情

NSNotificationCenter.defaultCenter().addObserver(self, selector: "notificationReceived:", name: "NotificationKey", object: nil)
NSNotificationCenter.defaultCenter().addObserverForName("NotificationKey", object: nil, queue: nil) { [weak self] notification in
    NSLog("Notification received in closure!")
}

@objc private func notificationReceived(notification: NSNotification) {
    NSLog("Notification received!")
}
然后,我将视图控制器作为观察者移除

NSNotificationCenter.defaultCenter().removeObserver(self)
移除观察者后,我仍然可以在闭包中看到NSLog,但在选择器函数中看不到NSLog。通知中心似乎正在执行关闭操作。我还注意到,如果self在闭包中被引用,那么闭包可能会导致一个retain循环(添加[weak self]可以解决这个问题,但是仍然调用NSLog行)

有人知道为什么关闭仍在处理通知吗

是否曾经有过在选择器上使用闭包的情况(我更喜欢闭包,因为它避免了神奇的字符串)?

addObserverForName(\uObject:queue:usingBlock:)
实际上返回一个您可以保留的对象。您应该将此对象传递给
removeObserver()


小更正:在将其传递给
removeObserver(:)
之前,您必须先打开
observer
,因为您声明它是可选的。啊,糟了。没有看到它返回了什么。谢谢我现在可以转换选择器了!(我讨厌选择器:P)
var observer: AnyObject?

// ...

observer = NSNotificationCenter.defaultCenter().addObserverForName("NotificationKey", object: nil, queue: nil) { [weak self] notification in
    NSLog("Notification received in closure!")
}

// ...

if let observer = observer {
    NSNotificationCenter.defaultCenter().removeObserver(observer)
}