Use cocoa bindings and threads

末鹿安然 提交于 2021-01-29 11:23:48

问题


I have a few labels bound to a few variables that are modified in other threads via GCD.
Now I've read that cocoa bindings are not thread safe but my app is running fine (the UI updates when the values of the variables are updated in a background thread)

Would it be the correct way to do the calculations in the background thread and if I need to change the variable value make this via

DispatchQueue.main.sync() {
   self.variable = newValue
}

? If cocoa bindings are not thread safe, why I never encountered any crash because of a "read" of the bound UI element while the value was written by a background process?

What is the preferred way to have a value bound to a UI element (via cocoa bindings) and also modify it by async threads?

Thanks!


回答1:


Yes, if you modify an object that is observed by Cocoa bindings, you should do so only on the main thread, and GCD dispatching the modification to the main thread is a good enough way to do that.

Yes, your app probably works fine most of the time, but that is likely luck based and not actually correct. The problem is that Cocoa bindings are based on Key Value Observation, and KVO notifications are posted on the thread that causes the mutation.

It’s also a complexity problem. As long as your app is relatively simple and fast, there’s much less chance of two threads running afoul of one another. Imagine when your app gets more complex and computationally intensive... and a problem crops up... but by this point you might have hundreds of places where you’re modifying bound properties from multiple threads. It’ll save you grief in the long run to just follow the rules. Use the main thread for updating bound to objects and try to keep bound properties to immutable, value-semantic types.



来源:https://stackoverflow.com/questions/57459408/use-cocoa-bindings-and-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!