0

My app has several notifications and observers to refresh the views when a user adds or deletes data.

Should I use a notification and observer for each type of data interaction? For example:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "categoryAdded"), object: nil)

And then for each notification:

NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "categoryAdded"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "transactionAdded"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "transactionDeleted"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "transactionEdited"), object: nil)

Or can I just use a single value:

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "dataUpdated"), object: nil)

And then use a single observer:

NotificationCenter.default.addObserver(self, selector: #selector(self.refresh), name: NSNotification.Name(rawValue: "dataUpdated"), object: nil)
BriScoLeg
  • 105
  • 1
  • 9
  • where is your several notifications ? you observe from different viewcontrollers ? https://stackoverflow.com/questions/24049020/nsnotificationcenter-addobserver-in-swift – roadRunner Oct 06 '20 at 15:52
  • @sekoyaz My app is a Tab Bar app. When a user updates data, I use notifications and observers in ViewDidLoad that have selectors that link to a `@objc func refresh()` function to refresh the data on the other controllers. – BriScoLeg Oct 08 '20 at 00:47

1 Answers1

0

I think for your case, your option to use a single value and a single observer would be the better choice since you do the same thing in the observer class (#selector(self.refresh)).

You might also consider using delegate pattern.