I'm writing an app that interfaces with Bluetooth, and for OO reasons I need to be able to notify 1 to many objects when Bluetooth events happen. I've got a custom Model object:
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++
}
}
...
}
As well as the Controller I'm trying to hook up with 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!")
}
...
}
I've confirmed that count is being incremented repeatedly, even after the view controller loads and registers as observer. I'm pretty sure no notifications are firing, but I don't know why. Do I need to add something to enable KVO in a custom NSObject? I'm using the latest iOS9 and Swift2.