【问题标题】:How to create an event loop in Objective C?如何在 Objective C 中创建事件循环?
【发布时间】: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 应用程序,所以我可能错过了明显的内容。如果我不得不猜测我做错了什么,我会假设:

我基本上被困在这一点上:我没有 GUI,我也不想要一个但无法找到运行事件循环的方法(假设这实际上是缺少的)。我该怎么做?

正如我所说,这实际上是我第一次尝试使用 Objective C,所以不要害怕说出显而易见的事实。

【问题讨论】:

  • 您的 MyCentralManager 实例可能没有被保留,因为委托属性 CBCentralManager 被声明为弱。如果您在管理器类中覆盖 dealloc,是否会在扫描完成之前调用它?
  • @PatrickGoley 会有任何链接/参考吗?我不确定什么会导致我的代码中的属性变弱。
  • 导致它变弱的不是您的代码,如果您查看 CBCentralManager 的标头,您会看到它的委托属性被声明为弱,这是指向您的管理器实例的唯一引用
  • @PatrickGoley 好的,我明白了。谢谢你的解释!

标签: objective-c macos bluetooth event-loop


【解决方案1】:

只需运行线程的运行循环

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]];

更多信息here

顺便说一句:您不必声明已经在协议中声明的方法。

【讨论】:

  • 感谢您的回答我还没有机会测试它,但很快就会。 Downvoter,你愿意解释一下你的投票吗?为什么你认为这是错误的?
  • 白痴:- 2 1 小时前 downvote -2 1 小时前 downvote Objective-C:将 NSString 附加到 NSException 原因 -2 1 小时前 downvote 如何验证金额文本值 -2 1 小时前downvote NSObject 类初始化 -2 1 小时前 downvote 类别与 iOS 中的实用程序类 -2 1 小时前 downvote NSPopUpButton 所选项目的整数值 -2 1 小时前 downvote 目标-c 中的 TDD:属性/构造函数注入或方法调配? -2 1 小时前 downvote 从 NSMutableArray 中删除特定项目 -2 1 小时前 downvote 将字符串添加到 NsMutableSets
  • 我认为您是连续投票的受害者?如果之前没有人捡起它,你应该在 meta 上提到它(有检测这种蹩脚行为的机制)
  • 我认为脚本会修复它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 1970-01-01
相关资源
最近更新 更多