简体   繁体   中英

Swift protocol called in objective-c not working

I am trying to get this swift protocol to work in an objective c file, but the function is not getting called for some reason. I want the didConnect() to be called when the device connects and didDisconnect() to be called when the device disconnects. I set a breakpoint in the centralManager did connect function and printed out delegate , it came back 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()
            }
        }

in the objective c file

    @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];

            }
}

You're very likely creating multiple KestrelDeviceConnect objects. One has a delegate of ViewController , and likely there's another that you're actually using for anything.

I suspect you meant this line, which creates a new KestrelDeviceConnect:

_kestrelVC = [[KestrelDeviceConnect alloc]init];

to be this:

_kestrelVC = [KestrelDeviceConnect singleton];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM