swift 一个NSObject扩展,允许您使用枚举作为常见KVO任务的关键路径。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 一个NSObject扩展,允许您使用枚举作为常见KVO任务的关键路径。相关的知识,希望对你有一定的参考价值。
extension NSObject {
func addObserver <RawType: RawRepresentable where RawType.RawValue == String>(observer: NSObject, forKeyPath keyPath: RawType, options: NSKeyValueObservingOptions, context: UnsafeMutablePointer<Void>) {
addObserver(observer, forKeyPath: keyPath.rawValue, options: options, context: context)
}
func removeObserver <RawType: RawRepresentable where RawType.RawValue == String>(observer: NSObject, forKeyPath keyPath: RawType) {
removeObserver(self, forKeyPath: keyPath.rawValue)
}
func removeObserver <RawType: RawRepresentable where RawType.RawValue == String>(observer: NSObject, forKeyPath keyPath: RawType, context: UnsafeMutablePointer<Void>) {
removeObserver(observer, forKeyPath: keyPath.rawValue, context: context)
}
func willChangeValueForKey <RawType: RawRepresentable where RawType.RawValue == String>(key: RawType) {
willChangeValueForKey(key.rawValue)
}
func didChangeValueForKey <RawType: RawRepresentable where RawType.RawValue == String>(key: RawType) {
didChangeValueForKey(key.rawValue)
}
}
Example:
enum OperationState: String {
case isExecuting, isFinished, isReady, isCancelled
}
thingToBeObserved?.addObserver(self,
forKeyPath: OperationState.isFinished,
options: [.Initial, .New],
context: someContext
)
thingToBeObserved?.removeObserver(self,
forKeyPath: OperationState.isFinished,
context: someContext
)
以上是关于swift 一个NSObject扩展,允许您使用枚举作为常见KVO任务的关键路径。的主要内容,如果未能解决你的问题,请参考以下文章
使用 Objective-C 类别扩展 Swift 类
扩展中的延迟加载属性(Swift)
Swift 扩展最佳实践
使用 NSObject 的 Swift 2.1 委托
PacketTunnelProvider 网络扩展不称为 Swift 3
使用 Swift iOS 中的 Javascriptcore 框架将 NSobject 传递给 javascript