NotificationCenter帖子更新主线程上的UI元素?

时间:2017-03-07 12:35:59

标签: swift3 grand-central-dispatch nsnotificationcenter

所以这就是我想要理解的:

示例:

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
}

现在我的问题是,如果我在我的项目中发布某个类的通知,并且该触发器不是由UI元素引起的我是否还需要使用包装didUpdateHistory函数内的任何内容主关闭还是我应该自己包装帖子?

同样重要的是你在哪里添加观察者以及从哪里发布通知?

1 个答案:

答案 0 :(得分:2)

你必须只打包邮局。

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

详细了解如何向特定线程发送通知 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Notifications/Articles/Threading.html