macos - OSX Cocoa Core-蓝牙委托(delegate)和 UI 更新线程安全

标签 macos cocoa thread-safety core-bluetooth cocoa-bindings

我有 OSX BLE 心率示例:https://developer.apple.com/library/mac/samplecode/HeartRateMonitor/Introduction/Intro.html 。此示例通过将 NSTextField 绑定(bind)到 heartRate 属性来更新心率。 heartRateperipheral:didUpdateValueForCharacteristic 中更新,从而相应地更新绑定(bind)的 NSTextView。是不是 peripheral:didUpdateValueForCharacteristic 在另一个线程上,但是由于控件的更新是由 Cocoa 在“幕后”处理的,所以这工作得很好?

我添加了另一个 NSTextView,并在其中创建了一个 socket ivar。此 ivar 也会在 peripheral:didUpdateValueForCharacteristic 中更新,并调用 [txtfldHR setIntegerValue:bpm]; 。这似乎也可以正常工作。但是从另一个线程通过 IBOutlet 更新 NSTextField 不是危险的(或者根本不应该工作)吗?如何在不使用绑定(bind)的情况下通过函数调用安全地更新 NSTextField?

我在 Android 中制作了一个类似的应用程序,我需要通过消息将心率值从 BLE 回调传递到 UI 线程,以便更新 UI 控件。

最佳答案

如果您查看示例代码,您将看到CBCentralManager使用以下代码初始化 -

manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];

如果您引用 queue 的文档initWithDelegate的参数,它说 -

The dispatch queue to use to dispatch the central role events. If the value is nil, the central manager dispatches central role events using the main queue.

这意味着您的各种蓝牙委托(delegate)事件将使用主队列执行。

如果您为委托(delegate)操作使用不同的队列,那么您需要通过类似 dispatch_async(dispatch_get_main_queue() ^{ //code }); 的方式在主队列上显式调度 UI 更新事件。

关于macos - OSX Cocoa Core-蓝牙委托(delegate)和 UI 更新线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29475655/

相关文章:

macos - Visual Studio for Mac的调试器总是提示 "program does not exist"

Excel-VBA : How to get size of selected array in vba code?

objective-c - moveItemAtPath。没有错误,但不工作

ruby-on-rails - 以线程安全的方式设置 Rails ActiveResource header

java - ConcurrentHashMap 上的竞争条件问题

java - 通知运行在不同对象中的线程

cocoa - QT 作为 MacOSX 上的 GUI 工具包会有 future 吗?

objective-c - NS 大纲 View : exception when edit a NSTextFieldCell bound to a NSTreeController

macos - Cocoa布局OSX(WebView - 填充左侧空间+ TextView - 右侧边栏固定宽度)如何?

macos - 如何使用ICCameraDevice拍照?