Skip to content

Instantly share code, notes, and snippets.

@dzindra
Last active August 6, 2017 20:26
Show Gist options
  • Select an option

  • Save dzindra/18372e4fde91388b80727269b191c7a4 to your computer and use it in GitHub Desktop.

Select an option

Save dzindra/18372e4fde91388b80727269b191c7a4 to your computer and use it in GitHub Desktop.
class NotificationHelper {
let notificationCenter: NSNotificationCenter
var observers: [AnyObject] = []
init(notificationCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter()) {
self.notificationCenter = notificationCenter
}
deinit {
observers.forEach { self.notificationCenter.removeObserver($0) }
}
func add(name: String, object: AnyObject? = nil, queue: NSOperationQueue? = NSOperationQueue.mainQueue(), block: (NSNotification) -> Void) {
observers.append(notificationCenter.addObserverForName(name, object: object, queue: queue, usingBlock: block))
}
func post(name: String, object: AnyObject? = nil, userInfo: [NSObject:AnyObject]? = nil, ensureMainThread: Bool = true) {
if ensureMainThread && !NSThread.isMainThread() {
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.notificationCenter.postNotificationName(name, object: object, userInfo: userInfo)
}
} else {
notificationCenter.postNotificationName(name, object: object, userInfo: userInfo)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment