我有 OSX BLE 心率示例:https://developer.apple.com/library/mac/samplecode/HeartRateMonitor/Introduction/Intro.html 。此示例通过将 NSTextField 绑定(bind)到 heartRate
属性来更新心率。 heartRate
在 peripheral: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/