Jad
Jad

Reputation: 2238

NotificationCenter post to update UI element on main thread?

I have this code in my project:

func viewDidLoad() {
  super.viewDidLoad()

  NotificationCenter.default.addObserver(
          self,
          selector: #selector(self.didUpdateHistory),
          name: NSNotification.Name.init("didUpdateHistory"),
          object: nil)
}

func didUpdateHistory() {
   // Update some UI elements
}

Now my question is: if I post the notification from some class in my project and that trigger wasn't caused by a UI element, do I still need to wrap the code in the didUpdateHistory func with DispatchQueue.main.async { ... } or should I wrap the post call itself?

Also, does it matter where you add the observer and from where you post the notification?

Upvotes: 2

Views: 2486

Answers (1)

pkc
pkc

Reputation: 8502

You have to wrap the post call only.

DispatchQueue.main.async {
    NotificationCenter.default.post(name: "didUpdateHistory", object: nil, userInfo: nil)
}

Read more about Delivering Notifications To Particular Threads https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Notifications/Articles/Threading.html

Upvotes: 7

Related Questions