I am creating a custom delegate in a class and trying to implement the protocol in my controller. But is not working as delegate is nil. This is how I am doing it :
BluetoothOperations.swit
protocol GetWatchCollectedData:NSObjectProtocol {
func getWatchCollectedData(COMMAND_ID : UInt8, data : NSData)
}
class BluetoothOperations: NSObject{
var getWatchCollectedData: GetWatchCollectedData?
func customFunc(){
getWatchCollectedData.getWatchCollectedData(ID,Data)
}
}
SomeController.swift
class SomeController: UIViewController {
let object = BluetoothOperations()
override func viewDidLoad() {
super.viewDidLoad()
object.getWatchCollectedData = self
}
}
extension SomeController: GetWatchCollectedData{
func getWatchCollectedData(COMMAND_ID : UInt8, data : NSData){
print("delegate working.")
}
}
I have also tried to make an object of class and assign BluetoothOperations's object. getWatchCollectedData = self in viewDidLoad but didn't work.
Any idea where I am doing it wrong ? Thanks.
Your code looks correct. And here is the a possible reason why it may fail. In your SomeController, you are creating object from your BluetoothOperations class and assigned delegate correctly.
HOWEVER, you must make sure that the object defined in your controller is sending out the delegate call. You could be having another instance of the BluetoothOperations and that is actually being used, AND IN THAT INSTANCE, the delegate is not set.
The easiest way to check this is to manually trigger the delegate in the object you created in your view controller. Try the following code to see if the delegate get triggered or not.
class SomeController: UIViewController {
let object = BluetoothOperations()
override func viewDidLoad() {
super.viewDidLoad()
object.getWatchCollectedData = self
object.customFunc()// Trigger the delegate function here
}
}
extension SomeController: GetWatchCollectedData{
func getWatchCollectedData(COMMAND_ID : UInt8, data : NSData){
print("delegate working.")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With