Observer Pattern in Swift

Abhishek Kumar
Aug 31, 2018 · 1 min read

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.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade