KVO不适用于自定义NSObject子类的属性

时间:2015-10-13 13:44:49

标签: ios swift bluetooth key-value-observing

我正在编写与蓝牙接口的应用程序,出于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。

1 个答案:

答案 0 :(得分:0)

确保使用count关键字声明dynamic属性。如果它无法解决您的问题,请检查this