Reputation: 4891
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.
Upvotes: 3
Views: 456
Reputation: 16436
You have correctly implemented delegate but not between proper classes
As you have created object of BluetoothOperations
in SomeController
and also in other View controller let's say SomeController1
Now The delegate is responsible for only relevant class only
like
`BluetoothOperations` (Call `customFunc`) ----> `SomeController1`
`BluetoothOperations` (Call `customFunc`) ----> `SomeController`
And you are trying like this
`SomeController1 ---> `BluetoothOperations` (Call `customFunc`) ----> SomeController`
This couldn't be achieved by this way,
As your SomeController1
and SomeController
are not in connection from anywhere
It is very difficult to suggest you a answer
you create delegate between SomeController1
and SomeController
both of them.
Hope it is clear to you
Upvotes: 1
Reputation: 25261
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.")
}
}
Upvotes: 2