Reputation: 23
I've been working with BLE programming for the past couple weeks with Xcode 9.3 (peripheral) and a Cypress PSoC 4 board (central). I've only been using one class, PressureViewController
, that implements the required methods (and some optional ones) from the CBCentralManagerDelegate
and CBPeripheralDelegate
protocols.
Everything works fine.
My limited knowledge of how best to use the same protocols across multiple classes is wanting.
I've got this other class now, MotorViewController
, and, while it has completely different functionalities than the PressureViewController
, it will need to implement the same BLE methods from those delegate protocols.
The flow of logic is essentially the same for both classes when using those methods. In the end, each class has a property (for the Pressure one, it's a uint32_t
representing voltage; for the Motor, it's an uint8_t
representing radial position.)
I don't want to have to "copy and paste" all those methods and create double versions of them specific to my new class. Is there a way to create one file that handles the CBCentralManagerDelegate
and CBPeripheralDelegate
methods, such that I can conform to whatever that may be in each of my classes? (In the future, I will be making more classes that need these delegate protocols.) Or, is there "no harm, no foul" by the copying and pasting of the methods?
Thanks, anthony
Upvotes: 0
Views: 47
Reputation: 6300
You could create a new class like MyBluetoothDevice
that implements CBCentralManagerDelegate
and CBPeripheralDelegate
methods. And then use it in PressureViewController and in MotorViewController. Whenever you need to setup a delegate, you pass the instance of MyBluetoothDevice
instead of "self".
You could have 2 instances of MyBluetoothDevice
each used in one of your view controllers, or maybe 1 shared instance (depending on your use cases).
This type of functionality sharing is an example of OOP composition. Another way is to use inheritance, but modern practice is to favour composition over inheritance.
If you want to pass information from your view controller to the MyBluetoothDevice, you just use properties and methods of MyBluetoothDevice, and call them.
If at some point in time you want to get information back from MyBluetoothDevice into the view controller, you can define your own delegate protocol - MyBluetoothDeviceDelegate
, and set your view controller as an observer of this delegate's events. Using a delegate is a safe bet, but other alternatives are to use handler/completion blocks or NSNotificationCenter to report events back to the view controllers.
Upvotes: 0