问题描述
我创建了一个单例类来与多个视图控制器进行交互。如何从单例类中通知有关蓝牙状态?
import UIKit
import CoreBluetooth
class MyBluetoothManager: CBCentralManagerDelegate,CBPeripheralDelegate{
static let shared = MyBluetoothManager()
let central = CBCentralManager(delegate: MyCentralManagerDelegate.shared,queue: nil,options: nil)
}
我将来将实现CBPeripheral的代表。如果有现有博客,建议我。
解决方法
您可以考虑使用NotificationCenter
。
在视图控制器中,您需要为自定义通知类型添加观察者。例如:
NotificationCenter.default.addObserver( self,selector: #selector( self.methodtohandle ),name: .yourcustomeventname,object: nil )
当不再需要/显示控制器时,不要忘记删除观察者:
NotificationCenter.default.removeObserver(self,object: nil)
在您的单例课程中,您将称其为“发布”:
NotificationCenter.default.post(name: .yourcustomeventname,object: somedata)