0

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.

1 Answers1

0

Make sure the count property is declared with the dynamic keyword. If it doesn't solve your problem, check this out.

Community
  • 1
  • 1
Arthur Gevorkyan
  • 2,069
  • 1
  • 18
  • 31
  • Whoa! Well, that did it. Thank you! I can't believe this 'dynamic' didn't show up in my Google-ings into KVO. Haven't learned of it at all until now, even with the thorough tutorials I've been running. I can't mark your answer as a solution yet, but thank you ^.^ – Merijn van Tooren Oct 13 '15 at 13:52
  • Accepting my answer will be highly appreciated :) Good luck coding, man :) – Arthur Gevorkyan Oct 13 '15 at 13:54