从 Swift 中的 ObjC class 观察 属性

Observe a property from an ObjC class in Swift

我正在使用第三方库,我有一个 ObjC 头文件。在这个头文件中有一个 属性 我想从我的 Swift 代码中观察到。我现在的问题是:我是否可以在没有 .m 文件的情况下以某种方式扩展 ObjC class,以便在 Swift 中更改时我可以观察到 属性?我想过使用 KVO,但我需要更改 ObjC 的实现 class?

感谢您的帮助

假设您的 Objective-C class 是 key-value observing compliant,您可以使用 addObserver(_:forKeyPath:options:context:)。这是一个例子:

// Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property NSString * name;
@property int age;

- (id) initWithName:(NSString *) name
                age:(int) age;

@end

// Person.m
#import "Person.h"

@implementation Person

- (id) initWithName:(NSString *) name
                age:(int) age
{
    if (self = [super init]) {
        self.name = name;
        self.age = age;
    }

    return self;
}

@end

在 Swift 结束:

extension Person {
    override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if let keyPath = keyPath,
            let change = change,
            let oldValue = change[NSKeyValueChangeOldKey],
            let newValue = change[NSKeyValueChangeNewKey] {

            print("'\(keyPath)' has changed from \(oldValue) to \(newValue)")
        }
    }
}

let p = Person(name: "John", age: 42)

// Start observing changes
// In this case, the object will observe itself
p.addObserver(p, forKeyPath: "name", options: [.New, .Old], context: nil)
p.addObserver(p, forKeyPath: "age", options: [.New, .Old], context: nil)

p.name = "Jack"
p.age = 50

// You must remove all observers before releasing the object
p.removeObserver(p, forKeyPath: "name")
p.removeObserver(p, forKeyPath: "age")