我正在编写与蓝牙接口的应用程序,出于OO原因,我需要能够在蓝牙事件发生时通知1到多个对象。我有一个自定义的Model对象:
class BluetoothModel: NSObject, CBCentralManagerDelegate {
var cBCentralManager: CBCentralManager!
var peripherals = [CBPeripheral]()
var count = 0
// MARK: - Singleton Definition
static let instance = BluetoothModel()
private override init() {
super.init()
cBCentralManager = CBCentralManager(delegate: self, queue: dispatch_get_global_queue(QOS_CLASS_UTILITY, 0))
}
// MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(central: CBCentralManager) {
cBCentralManager.scanForPeripheralsWithServices(nil, options: nil)
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
if !peripherals.contains(peripheral) {
peripherals.append(peripheral)
count++
}
}
...
}
与控制器I一样,我试图与KVO联系:
class MasterViewController: UITableViewController, CBCentralManagerDelegate {
...
override func viewDidLoad() {
super.viewDidLoad()
...
BluetoothModel.instance.addObserver(self, forKeyPath: "count", options: .New, context: nil)
}
...
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print("Change!")
}
...
}
即使在视图控制器加载并注册为观察者之后,我也确认计数正在重复递增。我很确定没有通知,但我不知道为什么。我是否需要添加一些内容以在自定义NSObject中启用KVO?我使用的是最新的iOS9和Swift2。