<Error>: [CoreBluetooth] API MISUSE: Cancelling connection for unused peripheral
我的场景:
[CoreBluetooth] API MISUSE: Cancelling connection for unused
peripheral , Did you forget to keep a reference to it?
这个错误是什么意思?
正如消息所建议的,您需要将CBPeripheral实例存储在一个对它保持强引用的地方。
一般来说,通过将指针存储在某个地方,可以获得对对象的强引用。例如,您可能有一个bluetouthConnectionManager保存一个已连接外围设备的列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | @implementation BluetoothConnectionManager - (instancetype)init { if(self = [super init]) { _knownPeripherals = [NSMutableArray array]; dispatch_queue_t centralQueue = dispatch_queue_create("com.my.company.app", DISPATCH_QUEUE_SERIAL); _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:centralQueue options:@{CBCentralManagerOptionShowPowerAlertKey : @YES}]; } return self; } - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { [_knownPeripherals addObject:peripheral]; } - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)cbPeripheral error:(NSError *)error { // This probably shouldn't happen, as you'll get the 'didConnectPeripheral' callback // on any connected peripherals and add it there. if(![_knownPeripherals containsObject:cbPeripheral]) { [_knownPeripherals addObject:cbPeripheral]; } [_centralManager connectPeripheral:cbPeripheral options:nil]; } @end |
或者,您可以修改此代码以引用单个连接的外围设备。
您还可以使用此功能编写以前的连接ID,以便在重新启动应用程序时尝试建立它们,如Apple Docs中所述。
最后,参考资料的几个链接:
- 目标C强与弱的区别
- IOS中强存储和弱存储的解释5
在"强引用和弱引用ios"上搜索将产生额外的结果。如果您使用的是ARC,只需拥有一个属性就可以创建一个强引用。无论如何,向数组中添加CBPeripheral实例也将创建强引用。