我不明白如何使用 block 删除通知的观察者。
var block = NotificationCenter.default.addObserver(forName: .notifName, object: obj, queue: OperationQueue.current, using: { notification in
NotificationCenter.default.removeObserver(block)
// Do stuff
})
这会出现编译器错误“变量在其自身初始值内使用”。我怎样才能删除这个观察者?
最佳答案
编译器提示,因为它不“知道”闭包 仅在创建并分配观察者之后执行 到变量。
您可以将观察者变量声明为隐式解包可选,因为当 block 执行:
var observer: NSObjectProtocol!
observer = NotificationCenter.default.addObserver(forName: ..., object: ..., queue: ...,
using: { notification in
NotificationCenter.default.removeObserver(observer)
// Do stuff
})
关于ios - 删除通知中心的观察者 - "Variable used within its own initial value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262369/