我遵循了 How to get the status of bluetooth (ON/OFF) in iphone programatically 的代码获取蓝牙状态。
但是当我通过后退导航按钮弹出 viewController 时,应用程序崩溃并出现以下错误。
[CoreBluetooth] XPC connection invalid
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x170261c80 of class CBCentralManager was deallocated while key value observers were still registered with it. Current observation info: ( Context: 0x1aa9c3710, Property: 0x170056b90> Context: 0x1aa9c3710, Property: 0x170056b00> Context: 0x1aa9c3710, Property: 0x170056b90> Context: 0x1aa9c3710, Property: 0x170056b00> )'
我试图在调用 viewWillDisappear 时删除上述观察者,但错误仍然存在。
[self.bluetoothManager removeObserver:self forKeyPath:@"state"];
[self.bluetoothManager removeObserver:self forKeyPath:@"delegate"];
我试过了
self.bluetoothManager.delegate = nil;
和
self.bluetoothManager = nil;
可悲的是,他们都没有作品。
请给予帮助。
更新:
我想在调用 - (void)detectBluetooth 时显示系统弹出警报,而蓝牙未打开。所以我加了
[self.bluetoothManager init];
在 - (void)detectBluetooth 中。
我发现犯了这个错误。
但我想不出另一种方法来显示默认弹出窗口(带有 SETTING 按钮)。
最佳答案
我找到了发生此错误的根本原因。
我对蓝牙管理器进行了多次初始化,因此它自己分配了多个观察者。
根据我的目的,在蓝牙未打开时显示系统警报弹出窗口。由于 init
会弹出警报,我需要先将 nil
设置为蓝牙管理器,然后再将 init
设置为。这是没有错误的。
这是我的最终代码:
if(!self.bluetoothManager)
{
// Put on main queue so we can call UIAlertView from delegate callbacks.
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
} else{
if (self.bluetoothManager.state != CBManagerStatePoweredOn) {
self.bluetoothManager = nil;
self.bluetoothManager = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];
}
}
[self centralManagerDidUpdateState:self.bluetoothManager];
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
switch(self.bluetoothManager.state)
{
case CBCentralManagerStatePoweredOn: [self pushViewController]; break;
case CBCentralManagerStateResetting:
case CBCentralManagerStateUnsupported:
case CBCentralManagerStateUnauthorized:
case CBCentralManagerStatePoweredOff:
default: break;
}
}
关于ios - Objective-C - 离开 ViewController 时 CBCentralManager NSInternalInconsistencyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41277655/