2016-11-03 86 views
1

我正在使用第三方庫,因爲我有一個ObjC頭文件。在這個頭文件中有一個屬性,我想從我的Swift代碼中觀察。我的問題是現在:我能以某種方式擴展ObjC類而不具有.m文件,以便在Swift中更改時可以觀察屬性?我想過使用KVO,但是我需要更改ObjC類的實現?在Swift中觀察ObjC類的屬性

感謝您的幫助

回答

0

假設你的Objective-C類是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 
斯威夫特

以上:

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")