Observer Pattern in Swift
In iOS Observer pattern can be achieved using these 3 ways:
- KVO
- NotificationCenter
- rxSwift framework(reactive programming)
Observer pattern have simple principle. If something changes in an Object then other objects who have subscribed for change in that property will be notified.
For Understanding KVO click on this link.
NotificationCenter:
NotificationCenter.default.post(name:Notification.Name("propertyChanged"), object: message)We call post when some property changes and it broadcast propertyChanged.
NotificationCenter.default.addObserver(self, selector: #selector(self.doSomething(notification:)), name: Notification.Name("propertyChanged"), object: nil)addObserver method is like subscribing to a broadcast from Notification center or listening to a notification.
doSomething method is called to perform desire actions when propertyChanged post is broadcasted.
@objc func doSomething(notification: NSNotification){
//do stuff
}Getting Notification Information from
NSNotification:
var name: NSNotification.Name: The name of the notification.
var object: Any?:The object associated with the notification.
var userInfo: [AnyHashable : Any]?The user information dictionary associated with the notification.
