简体   繁体   English

删除NotificationCenter的观察器-“变量在其自身的初始值内使用”

[英]Remove observer for NotificationCenter - “Variable used within its own initial value”

I do not understand how to remove an observer for a notification using a block. 我不明白如何使用块删除通知的观察者。

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

            // Do stuff
        })

This presents a compiler error "Variable used within its own initial value". 这会出现编译器错误“变量在其自身的初始值内使用”。 How can I remove this observer? 如何删除该观察者?

The compiler complains because it does not "know" that the closure is executed only after the observer has been created and assigned to the variable. 编译器抱怨是因为它不“知道”闭包仅创建观察者并将其分配给变量后才执行。

You can declare the observer variable as an implicitly unwrapped optional because it is guaranteed to have a value when the block is executed: 您可以将观察者变量声明为隐式展开的可选变量,因为在执行该块时可以保证它具有一个值:

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

    NotificationCenter.default.removeObserver(observer)

    // Do stuff
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM