我有一个类,它是CBPeripheral的一个子类。这样我就可以向CBPeripheral添加其他属性。
在centralManager委托方法didDiscoverPeripheral中,我将发现的外围设备转换为自己的CBPeripheral子类,然后尝试设置属性。
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
SCPCBPeripheral *discoveredPeripheral = (SCPCBPeripheral *)peripheral;
[discoveredPeripheral setCoreBluetoothManager:self];
}遗憾的是,这将不会转换为一个SCPCBPeripheral和错误,说“未识别的选择器发送到实例”。
有人知道为什么会这样吗?
如果有人想知道这是我的.h of SCPCBPeripheral
#import <CoreBluetooth/CoreBluetooth.h>
@class SCPCoreBluetoothCentralManager;
@interface SCPCBPeripheral : CBPeripheral
@property (nonatomic, strong) SCPCoreBluetoothCentralManager *coreBluetoothManager;
@end谢谢
发布于 2014-05-21 21:44:54
该对象是由不知道或不使用子类的其他东西创建的,而强制转换不会更改实例的实际类型。要更改类,需要将外设复制/重新创建为自定义子类(例如,通过编写+[SCPCBPeripheral peripheralWithPeripheral:] )
另一种选择是使用类别而不是子类将方法和属性直接添加到CBPeripheral。关于这种方法,有两件事值得注意。首先,您不能添加一个类别的ivars,尽管是there are workarounds。其次,添加的方法将被添加到类的所有实例中;您应该在添加的内容上使用前缀以避免名称冲突。
发布于 2014-05-21 21:42:56
不能只将CBPeripheral转换为自定义类。将其转换到该类不会迫使真正的对象知道如何响应您的自定义方法。相反,您应该创建一个自定义init方法,并将CBPeripheral存储在SPCBPeripheral实例中。从那时起,您应该使用SPCBPeripheral方法,而对象实际上将知道如何响应(因为它实际上属于这种类型)。
您实际需要实现的内容应该如下所示:
SPCBPeripheral *peripheral = [[SPCBPeripheral alloc]initWithDiscoveredPeripheral:peripheral];
[peripheral setCoreBluetoothManager:self];根据您的评论,您可以使用以下内容编写init方法:
-(id)initWithDiscoveredPeripheral:(CBPeripheral*)peripheral{
if(self = [super init]){
self.cbPeripheral = peripheral; //where cbPeripheral is a property of this class to store the real CBPeripheral
}
return self;
}https://stackoverflow.com/questions/23794215
复制相似问题