Last active
August 6, 2017 20:26
-
-
Save dzindra/18372e4fde91388b80727269b191c7a4 to your computer and use it in GitHub Desktop.
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
| 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