将逻辑分解成几个自包含的类总是好的设计。您绝对应该尝试根据服务或其他类别对代码进行分组。即使外围设备只有一个委托,您也可以轻松实现调度程序模式,您可以在其中注册各种服务实现和选择键(实际上是服务对象)并将调用调度到指定的服务处理程序。如果服务类实现了CPPeripheralDelegate
协议,那么这种设计将允许您单独测试/重用每个服务,如果您需要对代码进行最小的更改。
在伪 obj-c 代码中,调度程序外围委托如下所示:
// The ivar/property serving as the registry
NSMutableDictionary *registeredHandlers = [[NSMutableDictionary alloc] init];
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
// for each service create an instance of its handler class and
// add them to the registered handlers
for (CBService *service : peripheral.services) {
if (!registeredHandlers[service]) { // don't reinitialize if not needed
ExtendedCBPeripheralDelegate *serviceHandler = [self instantiateHandlerForService:service];
[registeredHandlers setObject:serviceHandler forKey:service];
[serviceHandler discoverCharacteristics]; // make this functionality self contained for the service
}
}
}
在服务或特性相关的回调中,应该实现调度。一个例子:
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
ExtendedCBPeripheralDelegate *serviceHandler = registeredHandlers[service];
[serviceHandler peripheral:peripheral didDiscoverCharacteristicsForService:service error:error];
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
ExtendedCBPeripheralDelegate *serviceHandler = registeredHandlers[characteristic.service];
[serviceHandler peripheral:peripheral didWriteValueForCharacteristic:characteristic error:error];
}
如果中央管理器断电,那么最好的解决方案是删除整个外围代理。不要为重新初始化而烦恼,而是计划处置。当然,如果需要,您可以通知服务处理程序即将销毁。