Skip to content

Instantly share code, notes, and snippets.

@Akki9326
Created March 4, 2019 12:49
Show Gist options
  • Save Akki9326/d73a2bbfa393c09749451f149588f6ff to your computer and use it in GitHub Desktop.
Save Akki9326/d73a2bbfa393c09749451f149588f6ff to your computer and use it in GitHub Desktop.
NSNotificationCenter Extension
/*
Copyright (c) 2011-present, NimbusKit. All rights reserved.
This source code is licensed under the BSD-style license found at http://nimbuskit.info/license
Extracted from NimbusKit: Swift Edition at https://github.com/nimbuskit/swift
*/
extension NSNotificationCenter {
/**
Adds an entry to the receiver’s dispatch table with an observer, a notification handler and optional criteria: notification name and sender.
This method allows you to specify a Swift object's instance method as the receiver for a notification. This is safer than using the selector variant because it allows the compiler to enforce the existence of the method.
Example:
class SimpleClass {
init() {
NSNotificationCenter.defaultCenter().addObserver(self, handler: SimpleClass.someNotification, name: "SomeNotification")
// Compared to the following which is prone to typos:
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("someNotification:"), name: "SomeNotification", object: nil)
}
func someNotification(notification: NSNotification) {
}
}
This method also has the following advantages:
- Lazy unregistering if the observer is deallocated. No need for explicit unregistering in the general case.
- Optional function arguments for easier method invocation. name, object, and queue are all truly optional.
If you wish to stop receiving notifications, you can retain the returned NSObjectProtocol and call removeObserver.
NSNotificationCenter.defaultCenter().removeObserver(self.retainedObserver)
*/
public func addObserver<T: AnyObject>(observer: T, handler: (T) -> (notification: NSNotification) -> (), name: String? = nil, object: AnyObject? = nil, queue: NSOperationQueue? = nil) -> NSObjectProtocol {
var generatedObserver: NSObjectProtocol?
generatedObserver = self.addObserverForName(name, object: object, queue: queue) { [weak weakObserver = observer, weak self] (notification) -> Void in
if weakObserver != nil {
handler(weakObserver!)(notification: notification)
} else { // Lazy removal from the notification center
self?.removeObserver(generatedObserver!)
}
}
return generatedObserver!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment