iOS6: CBPeripheral is being dealloc'ed while c

2019-02-08 11:51发布

问题:

I'm trying to connect to a bluetooth BTLE device. I have no problem discovering the peripheral.

However, when I attempt to connect to the peripheral, I received the following warning.

2013-04-05 22:10:36.110 CoreBluetooth[WARNING] 7DA9E322-D710-081B-4A9D-526DE546B13C, Name = "Find My Car Smarter", IsConnected = NO> is being dealloc'ed while connecting

Furthermore, neither of the relevant delegate methods are called:

didConnectPeripheral:
didFailToConnectPeripheral:

I've been struggling with this for hours... Please help.

回答1:

Short answer: You need to retain the peripheral.

Long explanation: Core Bluetooth does not know whether you are interested in this peripheral when it is discovered. Connecting to it is not enough, you need to retain it.

Add a property to the class where you are doing all that:

@property (strong) CBPeripheral     *connectingPeripheral;

And then assign the peripheral to this property when the device is discovered, before you return from didDiscoverPeripheral:

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
  DDLogVerbose(@"Discovered peripheral: %@ advertisement %@ RSSI: %@", [peripheral description], [advertisementData description], [RSSI description]);

  [central connectPeripheral:peripheral options:nil];
  self.connectingPeripheral = peripheral;
}