简体   繁体   English

是否可以在Swift中为协议实例设置观察者(KVO)

[英]Is it possible to set observer(KVO) for a protocol instance in Swift

Hi so I have a protocol called DTNavigationControllerDataSource which is defined as (leaving out the methods) 嗨,我有一个名为DTNavigationControllerDataSource的协议,该协议定义为(省略方法)

protocol DTNavigationControllerDataSource: NSObjectProtocol

Then, in my own custom UINavigationController subclass I have an instance variable of this protocol as follows. 然后,在我自己的自定义UINavigationController子类中,我具有此协议的实例变量,如下所示。

var dataSource: DTNavigationControllerDataSource?

Basically I need to know when an object becomes the dataSource. 基本上,我需要知道什么时候对象成为数据源。 ie The dataSource property is set. 即设置了dataSource属性。 So I can call the dataSource when it is initially set, to setup some state. 因此,可以在最初设置dataSource时调用它来设置一些状态。 I've thought about using KVO however NSObjectProtocol doesn't define any methods for doing so. 我曾考虑过使用KVO,但是NSObjectProtocol并未定义任何这样做的方法。 I'm not sure if this is even possible or if there is an alternative way outside of using KVO to know when the dataSource property inside DTNavigationController is set. 我不确定这是否可能,或者除了使用KVO来了解何时设置了DTNavigationController的dataSource属性之外,是否还有其他方法。 I've also tried didSet and willSet but Xcode threw errors at me, as I think that is only available for primitives. 我也尝试过didSetwillSet但是Xcode向我抛出了错误,因为我认为这仅适用于原语。

The didSet approach should work fine actually, had no issue with the following code in a playground (Xcode 7 GM): didSet方法实际上应该可以正常工作,在运动场中使用以下代码没有问题(Xcode 7 GM):

class DTNavigationController : UINavigationController {
    var dataSource: DTNavigationControllerDataSource? {
        didSet {
            print("new data source: \(dataSource)")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM