Swift objective-c 中调用的协议无效
Swift protocol called in objective-c not working
我试图让这个 swift 协议在 objective c 文件中工作,但由于某种原因没有调用该函数。我希望在设备连接时调用 didConnect()
,在设备断开连接时调用 didDisconnect()
。我在 centralManager did connect 函数中设置断点并打印出来 delegate
,它返回 nil
@objc protocol KestrelDeviceConnectDelegate {
@objc func didConnect()
@objc func didDisconnect()
}
@objcMembers
class KestrelDeviceConnect: NSObject{
static let singleton = KestrelDeviceConnect()
public var delegate: KestrelDeviceConnectDelegate?
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.isInitialReading = false
self.kestrelIsConnected = true
kestrelPeripheral.discoverServices(nil)
self.delegate?.didConnect()
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
self.kestrelIsConnected = false
self.delegate?.didDisconnect()
}
}
在 objective c 文件中
@interface ViewController ()<KestrelDeviceConnectDelegate> {
KestrelDeviceConnect<KestrelDeviceConnectDelegate> *_kestrelVC;
}
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
_kestrelVC = [[KestrelDeviceConnect alloc]init];
[_kestrelVC setDelegate:self];
}
-(void)didConnect{
[[self connectToKestrelButton] setHidden:NO];
}
}
您很可能会创建多个 KestrelDeviceConnect
对象。一个有 ViewController
的委托,并且可能还有另一个您实际用于任何事情的委托。
我怀疑你的意思是这一行,它创建了一个新的 KestrelDeviceConnect:
_kestrelVC = [[KestrelDeviceConnect alloc]init];
变成这样:
_kestrelVC = [KestrelDeviceConnect singleton];
我试图让这个 swift 协议在 objective c 文件中工作,但由于某种原因没有调用该函数。我希望在设备连接时调用 didConnect()
,在设备断开连接时调用 didDisconnect()
。我在 centralManager did connect 函数中设置断点并打印出来 delegate
,它返回 nil
@objc protocol KestrelDeviceConnectDelegate {
@objc func didConnect()
@objc func didDisconnect()
}
@objcMembers
class KestrelDeviceConnect: NSObject{
static let singleton = KestrelDeviceConnect()
public var delegate: KestrelDeviceConnectDelegate?
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
self.isInitialReading = false
self.kestrelIsConnected = true
kestrelPeripheral.discoverServices(nil)
self.delegate?.didConnect()
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
self.kestrelIsConnected = false
self.delegate?.didDisconnect()
}
}
在 objective c 文件中
@interface ViewController ()<KestrelDeviceConnectDelegate> {
KestrelDeviceConnect<KestrelDeviceConnectDelegate> *_kestrelVC;
}
@implementation ViewController
-(void)viewDidLoad {
[super viewDidLoad];
_kestrelVC = [[KestrelDeviceConnect alloc]init];
[_kestrelVC setDelegate:self];
}
-(void)didConnect{
[[self connectToKestrelButton] setHidden:NO];
}
}
您很可能会创建多个 KestrelDeviceConnect
对象。一个有 ViewController
的委托,并且可能还有另一个您实际用于任何事情的委托。
我怀疑你的意思是这一行,它创建了一个新的 KestrelDeviceConnect:
_kestrelVC = [[KestrelDeviceConnect alloc]init];
变成这样:
_kestrelVC = [KestrelDeviceConnect singleton];