ios - Objective-C - 离开 ViewController 时 CBCentralManager NSInternalInconsistencyException

标签 ios objective-c bluetooth core-bluetooth

我遵循了 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/

相关文章:

ios - 为什么委托(delegate)方法需要在 Swift 中公开?

android - Qt BLE Android : Characteristic update does not trigger characteristicChanged signal

javascript - react-native-maps:UrlTile 和 Polyline - zIndex/Overlaying 不工作

objective-c - XCode 调试器在“停止”按钮上使用 SIGKILL 停止

ios - 在纵向状态下强制旋转 UIViewController

iphone - UIDocumentInteractionController 导致未知应用程序标识符 com.apple.mobilemail 失败错误

java - 在 Java 中编码可变长度的 utf8 字节数组

ios - 游戏套件和 iPhone

ios - 返回第四个 View 时分段控件颜色不显示

ios - 单例设计模式以及不同类型之间的区别?