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
How to removeObserver in Swift 5 using addObserver closure method
Set your observer object to current view controller.
From apple doc.s, object is
The object whose notifications the observer wants to receive; that is,
only notifications sent by this sender are delivered to the observer.
NotificationCenter.default.addObserver(forName: UIApplication.didBecomeActiveNotification,
object: self,
queue: nil) { [weak self] notification in
guard let self = self else { return }
self.loadWeather(notification.object)
}
Removing observer from NotificationCenter
deinit {
NotificationCenter.default.removeObserver(self)
}
ANOTHER WAY
You can also make copy of Notification Observer object and remove it from NotificationCenter
in deinit
.
let notificationCenter = NotificationCenter.default
var loadWeatherObserver: NSObjectProtocol?
override func viewDidLoad() {
super.viewDidLoad()
loadWeatherObserver = notificationCenter.addObserver(forName: UIApplication.didBecomeActiveNotification,
object: nil,
queue: nil) { [weak self] notification in
guard let self = self else { return }
self.loadWeather(notification.object)
}
}
deinit {
if (loadWeatherObserver != nil) {
notificationCenter.removeObserver(loadWeatherObserver!)
}
}
Swift NotificationCenter remove observer quickest way
@Sh_Khan is right:
NotificationCenter.default.removeObserver(self)
You can get even further, as mentioned in the Apple Documentation:
If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.
How to safely removeObserver (Swift)
I think you should use code
NSNotificationCenter.defaultCenter().removeObserver(self)
Explain:
You have mistake here: You are using NSNotification & NSNotificationCenter so you have to using this code above to remove observe.
you have use code for KVO to remove observer so it will wrong.
More detail you can read at here. Key-Value-Observing
NSNotificationCenter: Removing an Observer in Swift
When you use the 'blocks' based approach to observing notifications then self
isn't in fact the observer. The function returns an object which acts as the observer:
func addObserverForName(_ name: String?,
object obj: AnyObject?,
queue queue: NSOperationQueue?,
usingBlock block: (NSNotification!) -> Void) -> NSObjectProtocol
You need to keep a reference to this returned object and pass it in as the observer when you call removeObserver
It's explained well in the Apple Doc here
Best Place to Remove NotificationCenter Observer in Swift Struct
From iOS 9 and above, it's not necessary to remove NotificationCenter
observers as they are automatically removed.
If you are concerned about observes stuck in memory anyway, you should call the removal from a class that is handling the struct.
Related Topics
How to Add Multiple Collection Views in a Uiviewcontroller in Swift
How to Center a Popoverview in Swift
Swift Doesn't Convert Objective-C Nserror** to Throws
Creating Custom Info Window in Swift with the Google Maps iOS Sdk
Using Uiimagepickercontroller in Landscape Orientation
Application Crashed While Importing Songs from Ipod Library in iPhone for iOS 5.0
Uitextfield Securetextentry Bullets with a Custom Font
How to Load an Uiimage into a Swiftui Image Asynchronously
How to Make a Button Continually Call a Function When Held Down (Spritekit)
Optional Binding with Try? and As? Still Produces an Optional Type
Switch Cameras with Avcapturesession
Uibutton Fails to Properly Register Touch in Bottom Region of iPhone Screen
How to Dynamically Change the Font Size in Auto Layout iOS
Entitlements File Do Not Match Those Specified in Your Provisioning Profile.(0Xe8008016)