使用可可绑定和线程 [英] Use cocoa bindings and threads

查看:48
本文介绍了使用可可绑定和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些标签绑定到一些变量,这些变量通过GCD在其他线程中进行了修改.
现在,我了解到可可绑定不是线程安全的,但是我的应用运行良好(当在后台线程中更新变量的值时,UI会更新)

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
}

?如果可可绑定不是线程安全的,为什么在值由后台进程写入时,由于绑定的UI元素被读取",我为什么从未遇到任何崩溃?

? 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?

将值绑定到UI元素(通过可可绑定)并通过异步线程对其进行修改的首选方法是什么?

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

谢谢!

推荐答案

是的,如果您修改了可可绑定所观察到的对象,则应仅在主线程上进行此操作,并且GCD将修改分派给主线程是一种足够好的方法.

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.

是的,您的应用在大多数情况下都可以正常运行,但这很可能是靠运气,实际上并不正确.问题在于,可可绑定基于键值观察",并且KVO通知发布在导致突变的线程上.

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.

这篇关于使用可可绑定和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆