[英]Observe a property from an ObjC class in Swift
我正在使用第三方庫,我有一個ObjC頭文件。 在這個頭文件中有一個我希望從我的Swift代碼中觀察到的屬性。 我現在的問題是:我可以以某種方式擴展ObjC類而不使用.m文件,以便在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
在斯威夫特:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.