Introducing HSNotifications. A simple, sensible, easy-to-use wrapper around NSNotificationCenter
Let’s jump straight in. I mostly use notifications to keep my UI up to date. That means ViewControllers end up with a bunch of observers that need to be activated and de-activated with the ViewController lifecycle
Easy ViewController Integration
class ViewController: NSViewController, HSHasObservers {
override func viewDidLoad() {
super.viewDidLoad()
//Create and add
HSObserver.init(forName: Foo.didAThing,
using: { (notif) in
//Do Something
}).add(to: self)
//Monitor multiple notifications
HSObserver.init(forNames: [Bar.oneThing,Bar.anotherThing] ,
activate:true,
using: { (notif) in
//Do Something Else
}).add(to: self)
}
override func viewWillAppear() {
super.viewWillAppear()
activateObservers()
}
override func viewDidDisappear() {
super.viewDidDisappear()
deactivateObservers()
}
}
Taking this step by step:
ViewController uses the protocol HSHasObservers
This allows us to add observers to the ViewController (they are stored in the observers array)
Next we create an HSObserver object. The block will be triggered by any Foo.didAThing notification.
We take sensible defaults
- Assume you want to use NSNotificationCenter.default
- Assume you want your block to fire on the main queue
- Assume you don’t care what object broadcasts the notification.
(Of course – you can override any of these if you want to.)
The observer is added to the ViewController with .add(to:self)
Next we add an HSObserver to observe multiple Notifications
Finally, the observers are activated and deactivated in viewWillAppear and viewDidDisappear
When the ViewController is released, they are cleaned up automatically.
Standalone Observers
var waveObserver:HSObserver
init() {
waveObserver = HSObserver.init(forName: Watcher.wave,
using: { (notif) in
//Do Something
})
//activate
waveObserver.activate()
//deactivate
waveObserver.deactivate()
}
HSObserver objects can be stored as a standard variable.
This allows them to be activated and deactivated.
They clean up properly when they are released with the owning object.
There are of course lots of options available here.
/// Create observer
///
/// - parameter name: notification name
/// - parameter obj: object to observe (default nil)
/// - parameter queue: queue to run the block on (default main)
/// - parameter center: notification center (default NotificationCenter.default)
/// - parameter block: block to run (beware of retain cycles!)
///
/// - returns: unactivated manager. Call activate() to start
convenience init(forName name: NSNotification.Name,
object obj: Any? = nil,
queue: OperationQueue? = .main,
center newCenter: NotificationCenter = NotificationCenter.default,
activate: Bool = false,
using block: @escaping (Notification) -> Swift.Void)
Get HSNotification at GitHub