【发布时间】:2015-08-31 01:13:52
【问题描述】:
我正在尝试使用CoreBluetooth 模块在命令行 OSX 应用程序中列出所有检测到的蓝牙设备。
到目前为止,我所拥有的看起来像这样:
@import CoreBluetooth;
@interface MyCentralManager : NSObject<CBCentralManagerDelegate>
- (void) centralManagerDidUpdateState: (CBCentralManager *) central;
- (void) centralManager:(CBCentralManager *) central
didDiscoverPeripheral:(CBPeripheral *) peripheral
advertisementData:(NSDictionary *) advertisementData
RSSI:(NSNumber *)RSSI;
@end
@implementation MyCentralManager
- (void) centralManagerDidUpdateState: (CBCentralManager *) central
{
NSLog(@"State changed...");
}
- (void) centralManager:(CBCentralManager *) central
didDiscoverPeripheral:(CBPeripheral *) peripheral
advertisementData:(NSDictionary *) advertisementData
RSSI:(NSNumber *)RSSI
{
NSLog(@"Discovered %@", peripheral.name);
}
@end
int main() {
MyCentralManager* myCentralManager = [[MyCentralManager alloc] init];
CBCentralManager* cbCentralManager = [[CBCentralManager alloc] initWithDelegate:myCentralManager queue:nil options:nil];
NSLog(@"Scanning devices now !");
[cbCentralManager scanForPeripheralsWithServices:nil options:nil];
sleep(5); // Wait 5 seconds before stopping the scan.
[cbCentralManager stopScan];
NSLog(@"Scanning devices ended.");
return 0;
}
现在这根本不起作用,因为我从来没有得到任何 "State changed..." 或 "Discovered ..." 日志输出。
我之前从未真正编写过任何 Objective C 应用程序,所以我可能错过了明显的内容。如果我不得不猜测我做错了什么,我会假设:
-
I actually have to wait for the
CentralManagerto be in the appropriate state before starting the scan。 - 我从来没有真正进入过状态改变的委托方法,所以我认为我的第一个错误是:不仅仅是
sleep()'ing,我必须运行某种事件循环,以便底层系统具有有机会通知我状态变化。
我基本上被困在这一点上:我没有 GUI,我也不想要一个但无法找到运行事件循环的方法(假设这实际上是缺少的)。我该怎么做?
正如我所说,这实际上是我第一次尝试使用 Objective C,所以不要害怕说出显而易见的事实。
【问题讨论】:
-
您的 MyCentralManager 实例可能没有被保留,因为委托属性 CBCentralManager 被声明为弱。如果您在管理器类中覆盖 dealloc,是否会在扫描完成之前调用它?
-
@PatrickGoley 会有任何链接/参考吗?我不确定什么会导致我的代码中的属性变弱。
-
导致它变弱的不是您的代码,如果您查看 CBCentralManager 的标头,您会看到它的委托属性被声明为弱,这是指向您的管理器实例的唯一引用
-
@PatrickGoley 好的,我明白了。谢谢你的解释!
标签: objective-c macos bluetooth event-loop