Ios 子类CBP未转换为正确的类型

Ios 子类CBP未转换为正确的类型,ios,objective-c,bluetooth,bluetooth-lowenergy,core-bluetooth,Ios,Objective C,Bluetooth,Bluetooth Lowenergy,Core Bluetooth,我有一个类是cbperipal的子类。这样我就可以将其他属性添加到CBPeripheral 在centralManager委托方法didiscoverperipal中,我将发现的外围设备强制转换为自己的cbperipal子类,然后尝试设置我的属性 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDicti

我有一个类是
cbperipal
的子类。这样我就可以将其他属性添加到
CBPeripheral

在centralManager委托方法
didiscoverperipal
中,我将发现的外围设备强制转换为自己的
cbperipal
子类,然后尝试设置我的属性

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    SCPCBPeripheral *discoveredPeripheral = (SCPCBPeripheral *)peripheral;
    [discoveredPeripheral setCoreBluetoothManager:self];
}
遗憾的是,这不会强制转换为
SCPCBPeripheral
,并会出现“无法识别的选择器已发送到实例”的错误

有人知道为什么会这样吗

如果有人想知道这是我的SCPCB的.h

#import <CoreBluetooth/CoreBluetooth.h>

@class SCPCoreBluetoothCentralManager;

@interface SCPCBPeripheral : CBPeripheral

@property (nonatomic, strong) SCPCoreBluetoothCentralManager *coreBluetoothManager;

@end
#导入
@SCPCoreBluetoothCentralManager类;
@接口SCPCBperipal:CBperipal
@属性(非原子、强)SCPCoreBluetoothCentralManager*核心BluetoothManager;
@结束

谢谢

您不能将
CBPeripheral
强制转换为自定义类。将其强制转换到该类不会迫使真实对象知道如何响应自定义方法。相反,您应该创建一个自定义init方法,并将
cbperipal
存储在
spcbperipal
实例中。从那时起,您应该使用
spcbperipal
方法,对象将实际知道如何响应(因为它实际上是那种类型的)

您实际需要实现的应该如下所示:

SPCBPeripheral *peripheral = [[SPCBPeripheral alloc]initWithDiscoveredPeripheral:peripheral];
[peripheral setCoreBluetoothManager:self];
-(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;
}
根据您的评论,您可以使用以下内容编写init方法:

SPCBPeripheral *peripheral = [[SPCBPeripheral alloc]initWithDiscoveredPeripheral:peripheral];
[peripheral setCoreBluetoothManager:self];
-(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;
}

该对象是由不知道或不使用子类的其他对象创建的,并且强制转换不会更改实例的实际类型。要更改类,您需要将外围设备复制/重新创建为自定义子类(例如,通过编写
+[SCPCBPeripheral-PeripheraldWithPeripheral:


另一种选择是使用类别而不是子类将方法和属性直接添加到
cbperipal
。关于这种方法,有两件事需要注意。首先,您不能添加带有类别的IVAR。其次,您添加的方法将添加到类的所有实例中;您应该在添加内容上使用前缀,以避免名称冲突。

此init方法将包含什么内容?我在想这个问题,但对于如何使用CBP初始化子类感到困惑。请查看我的编辑。这是一个可以编写的init方法的快速示例。不过我只是在飞行中写的。谢谢你的快速回复。在我的子类中,我没有cbperipal的属性,因为这就是为什么我想要子类化,这样所有的cbperipal方法都可以在我的scpcbperipal上调用。在不检查CbPeripal的每个属性的情况下,是否有方法使用传入的CbPeripal的所有属性初始化我的子类?不必使其成为CbPeripal的子类,您只需创建一个包装类来扩展NSObject并实现CbPeripheraldegate协议,然后将CBPeripheral存储在其中。或者你可以像Josh Caswell说的那样做一个分类。我已经决定不将其子类化,因为我只想让用户编写[peripheral connect],而不是让中央管理器来编写。感谢Guystella的谎言,我真的很喜欢能够去[peripheral connect],所以我使用
objc\u setAssociatedObject
为一个类别添加了一个属性