-
Notifications
You must be signed in to change notification settings - Fork 3
NotificationCenter Functions
Pablo Villar edited this page Mar 20, 2017
·
2 revisions
When assigning a function to a NotificationCenter
, it must:
- Include the notification object in its signature.
- Never be called directly from your code.
Good
func method(calledFrom notification: NSNotification) {
// It's clear that this method is going to be called from a notification.
}
NotificationCenter.default.addObserver(self, selector: #selector(method(calledFrom:)), name: "GoodExample", object: nil)
Bad
func method() {
// You can't know if this method was called from a notification or from somewhere else...
}
NotificationCenter.default.addObserver(self, selector: #selector(method), name: "BadExample", object: nil)
- Separation of concerns. You can easily separate out which methods are expected to be called by notification center and which are not.
- It avoids confusions.
- It prevents runtime crashes that may be caused by removing a method that you might think is not being used, but it's actually being called by notification center at runtime.
- By appending an
Notification
object to the method signature, you won't be able to call it from your code, because you won't have a notification object to pass in.