2016-12-22 22 views
0

我跟着How to get the status of bluetooth (ON/OFF) in iphone programatically的代碼來獲取藍牙的狀態。Objective C - CBCentralManager NSInternalInconsistencyException退出ViewController時

但是,當我通過後退導航按鈕彈出viewController時,應用程序崩潰,出現以下錯誤。

[CoreBluetooth] XPC connection invalid 

***終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,原因:「一個實例0x170261c80類CBCentralManager被釋放,而鍵值觀察家仍用它註冊。現有的觀測信息:(背景:0x1aa9c3710,物業:0x170056b90>上下文:0x1aa9c3710,物業:0x170056b00>上下文:0x1aa9c3710,物業:0x170056b90>上下文:0x1aa9c3710,物業:0x170056b00>)」

我試圖刪除觀察者在調用viewWillDisappear時稱上面提到,但是錯誤仍然存​​在。

[self.bluetoothManager removeObserver:self forKeyPath:@"state"]; 
[self.bluetoothManager removeObserver:self forKeyPath:@"delegate"]; 

我試着

self.bluetoothManager.delegate = nil; 

而且

self.bluetoothManager = nil; 

可悲的是他們都沒有工作。

請給予幫助。

更新:

我想顯示系統彈出警報,而尚未打開藍牙打電話時ON - (無效)detectBluetooth。所以我加

[self.bluetoothManager init]; 

in - (void)detectBluetooth。

我發現發生錯誤。

但我找不出另一種方法來顯示默認彈出窗口(其中設置按鈕)。

回答

1

我發現了這個錯誤發生的根源。

我做了多個init到藍牙管理器,所以它分配了多個觀察者本身。

基於我的目的,在藍牙未打開時顯示系統警報彈出窗口。由於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; 
    } 
} 
+0

建議:你可以使用一個Singleton對象爲它(有可能委託/通知),讓您的推,或簡單地用一個延遲初始化:' - (CBCentralManager )bluetoothManager {if(!self.bluuetoothManager){_ bluetoothManager = alloc/init/settings等}} return _bluetoothManager;}'在你的代碼中,總是用'self.bluetoothManager'調用你的中央管理器 – Larme

+0

非常感謝建議! – KTang

相關問題