简体   繁体   中英

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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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