NotificationCenter发布更新主线程上的UI元素?

Jad*_*Jad 2 grand-central-dispatch nsnotificationcenter swift3

我的项目中有以下代码:

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
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是:如果我发布一些班级通知我的项目,并且触发不是由UI元素造成的,我还需要包装代码与didUpdateHistory FUNC DispatchQueue.main.async { ... }或者我应该换行后调用本身?

另外,在何处添加观察者以及从何处发布通知是否重要?

pkc*_*456 5

你必须只包住后调用。

DispatchQueue.main.async {
    NotificationCenter.default.post(name: "didUpdateHistory", object: nil, userInfo: nil)
}
Run Code Online (Sandbox Code Playgroud)

阅读有关将通知传递到特定线程的更多信息 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Notifications/Articles/Threading.html