Last active
October 12, 2015 13:08
-
-
Save qmchenry/822d3d15cea03f17c559 to your computer and use it in GitHub Desktop.
NSNotification handler protocol extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol NotificationHandler { | |
var name: String { get } | |
func post(object: AnyObject?, userInfo: [NSObject : AnyObject]?) | |
func observe(observer: AnyObject, selector: Selector, object: AnyObject?) | |
func remove(observer: AnyObject, object: AnyObject?) | |
static func remove(observer: AnyObject) | |
} | |
public extension NotificationHandler { | |
func post(object: AnyObject? = nil, userInfo: [NSObject : AnyObject]? = nil) { | |
NSNotificationCenter.defaultCenter().postNotificationName(name, object: object, userInfo: userInfo) | |
} | |
func observe(observer: AnyObject, selector: Selector, object: AnyObject? = nil) { | |
NSNotificationCenter.defaultCenter().addObserver(observer, selector: selector, name: name, object: object) | |
} | |
func remove(observer: AnyObject, object: AnyObject? = nil) { | |
NSNotificationCenter.defaultCenter().removeObserver(observer, name: name, object: object) | |
} | |
static func remove(observer: AnyObject) { | |
NSNotificationCenter.defaultCenter().removeObserver(observer) | |
} | |
} | |
// Example 1: | |
enum Notification: String, NotificationHandler { | |
case SuperImportantThing | |
case SystemTimeChanged | |
var name: String { | |
switch self { | |
case .SystemTimeChanged: return NSSystemClockDidChangeNotification | |
default: return rawValue | |
} | |
} | |
} | |
// elsewhere in code... | |
Notification.SystemTimeChange.observe(self, Selector("handleTimeChange:")) | |
Notification.SuperImportantThing.post() | |
Notification.remove(self) | |
// ------ | |
// Example 2: | |
extension String: NotificationHandler { | |
public var name: String { | |
return self | |
} | |
} | |
"extensions_rule".post() // Cool that this works, but please don't :-) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment