2016-11-03 6 views
1

私はObjCヘッダファイルを持っているサードパーティのライブラリを使用しています。このヘッダーファイルには私のSwiftコードから見たいプロパティがあります。私の質問は今:私は何らかの方法で、私はプロパティがSwiftで変更されるたびに観測できる.mファイルを持たずにObjCクラスを拡張できますか?私はKVOの使用を考えましたが、ObjCクラスの実装を変更する必要がありますか?あなたのObjective-Cのクラスを想定すると、あなたの助けSwiftのObjCクラスからプロパティを観察します。

答えて

0

ため

おかげで、あなたはaddObserver(_:forKeyPath:options:context:)を使用することができ、key-value observing compliantです。ここでは例です:

// 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") 
関連する問題