Search code examples
swiftnsnotificationcenterobservers

Can Notification Center Observe Value Change Swift


Is something like this possible?

Observe SearchUtil().getSearchList().count so whenever the count changes or equals to a specific int value(SearchUtil().getSearchList().count == 0) run @objc func OnAppBecameActive()

  NotificationCenter.default.addObserver(self, selector: #selector(OnAppBecameActive), name: SearchUtil().getSearchList().count, object: nil)

Solution

  • Yes, there are several ways to do this. The thing you want to observe needs to be a property, not the outcome of an expression. If this is (or can be) an NSObject, you can use Key-Value Observing. If not, you can make this a @Published property and set up a pipeline that processes each change.