Is removing a NotificationCenter observer that was created with closure syntax by name adequate?
You absolutely need to store the return value in a property and remove that later on.
From https://developer.apple.com/reference/foundation/nsnotificationcenter/1411723-addobserverforname:
Return Value
An opaque object to act as the observer.
When you call any one of the removeObserver
methods, the first parameter is the observer to remove. When you set up a block to respond to a notification, self
is not the observer, NSNotificationCenter
creates its own observer object behind the scenes and returns it to you.
Note: as of iOS 9, you are no longer required to call
removeObserver
fromdealloc
/deinit
, as that will happen automatically when the observer goes away. So, if you're only targeting iOS 9, this may all just work, but if you're not retaining the returned observer at all, the notification could be removed before you expect it to be. Better safe than sorry.
Where to remove observer for NSNotification in Swift?
Use below method which functions same as dealloc
.
deinit {
// Release all resources
// perform the deinitialization
}
A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how intializers are written with the init keyword. Deinitializers are only available on class types.
Swift Deinitializer
Extending NotificationCenter
It sounds like you need something like
extension NotificationCenter {
static func dispatch(key: String, payload: [String: String] = [:]) {
self.default.post(name: NSNotification.Name(rawValue: key), object: nil, userInfo: payload)
}
static func observe(key: String, handler: @escaping (Notification) -> Void) {
self.default.addObserver(forName: NSNotification.Name(rawValue: key), object: nil, queue: .main, using: handler)
}
}
Related Topics
Arkit - How to Put 3D Object on Qrcode
How to Alloc/Dealloc Unsafe Pointers in Swift
Scenekit -- How to Get Animations for a .Dae Model
How to Quit Swift Repl Without Using Ctrl-D
Storyboard Entry Point Missing
Present Actionsheet in Swiftui on iPad
How to Simulate Traits/Mixins in Swift
How to Avoid Using Anypublisher/Erasetoanypublisher All Over the Place
How to Recognize Continuous Touch in Swift
Nsuserdefaults in Swift - Implementing Type Safety
Get the Current Position of Scrollview in Swiftui
Swift - How to Save Audio from Avaudioengine, or from Audioplayernode? If Yes, How
Scenekit - Get Direction of Camera
Value for Swift_Version Cannot Be Empty
Class Level or Struct Level Method in Swift Like Static Method in Java