我正在使用一个第三方库,为此我有一个ObjC头文件。在此头文件中,有一个我想从我的Swift代码中观察到的属性。我的问题现在是:我可以在没有.m文件的情况下以某种方式扩展ObjC类,以便无论何时在Swift中对其进行更改时都可以观察到该属性吗?我曾考虑过使用KVO,但随后我需要更改ObjC类的实现吗?
谢谢你的帮助
假设您的Objective-C类符合键值观察标准,则可以使用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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句