Ios 移除NotificationCenter的观察者-“;在其自身初始值内使用的变量;

Ios 移除NotificationCenter的观察者-“;在其自身初始值内使用的变量;,ios,iphone,swift,notificationcenter,Ios,Iphone,Swift,Notificationcenter,我不明白如何使用块删除通知的观察者 var block = NotificationCenter.default.addObserver(forName: .notifName, object: obj, queue: OperationQueue.current, using: { notification in NotificationCenter.default.removeObserver(block) // Do stuff

我不明白如何使用块删除通知的观察者

var block = NotificationCenter.default.addObserver(forName: .notifName, object: obj, queue: OperationQueue.current, using: { notification in
            NotificationCenter.default.removeObserver(block)

            // Do stuff
        })

这将显示一个编译器错误“变量在其自身初始值内使用”。如何删除此观察者?

编译器抱怨,因为它不“知道”闭包 仅在创建并分配观察者后执行 对变量进行修改

您可以将observer变量声明为隐式展开的可选变量,因为当块 已执行:

var observer: NSObjectProtocol!
observer = NotificationCenter.default.addObserver(forName: ..., object: ..., queue: ...,
                                                  using: { notification in

    NotificationCenter.default.removeObserver(observer)

    // Do stuff
})

伟大的苹果的文档展示了一个在Objective-C中工作的例子,这对于Swift来说有点棘手。