Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainbriche/045038f6ebf8056e3ab580c04c96e17a to your computer and use it in GitHub Desktop.
Save romainbriche/045038f6ebf8056e3ab580c04c96e17a to your computer and use it in GitHub Desktop.
NSNotificationCenter extension for safe Swift instance method support
/*
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, name: String? = nil, object: AnyObject? = nil, queue: NSOperationQueue? = nil, handler: (T) -> (notification: NSNotification) -> ()) -> 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