【问题标题】:KVO not working for attribute of custom NSObject subclassKVO 不适用于自定义 NSObject 子类的属性
【发布时间】:2015-10-13 13:44:48
【问题描述】:

我正在编写一个与蓝牙接口的应用程序,出于 OO 的原因,我需要能够在蓝牙事件发生时向多个对象通知 1。我有一个自定义模型对象:

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++
        }
    }
    ...
}

以及我尝试连接 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!")
    }
    ...
}

我已经确认 count 会重复递增,即使在视图控制器加载并注册为观察者之后也是如此。我很确定没有通知正在触发,但我不知道为什么。我是否需要添加一些东西来在自定义 NSObject 中启用 KVO?我正在使用最新的 iOS9 和 Swift2。

【问题讨论】:

    标签: ios swift bluetooth key-value-observing


    【解决方案1】:

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

    【讨论】:

    • 哇!嗯,做到了。谢谢!我不敢相信这种“动态”没有出现在我对 KVO 的 Google 搜索中。直到现在才完全了解它,即使我已经运行了详尽的教程。我还不能将您的答案标记为解决方案,但谢谢^.^
    • 接受我的回答将不胜感激 :) 祝编码好运,伙计 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多