ios - 在 Swift 中观察 ObjC 类的属性

标签 ios objective-c swift property-observer

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

谢谢你的帮助

最佳答案

假设您的 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

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

关于ios - 在 Swift 中观察 ObjC 类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404675/

相关文章:

ios - Realm 集合通知和 Collection View 计数之间的不同步

ios - ios8 中的 UIDocumentInteractionController presentOptionsMenuFromBarButtonItem 错误-提供的事件项目未知

ios - 快速在 UITABLEVIEW 上向右滑动时添加操作

ios - 如何关闭 ios 中自定义文本字段的键盘

xcode - 没想到发现无

ios - 具有自动布局的 UIScrollView 内部具有动态高度的容器 View

objective-c - 重绘问题 Objective-c

ios - 如何从一个 iPhone 应用程序向其他应用程序发送小消息(2 种不同的手机)

ios - 可以从 json 文件加载元组数组吗?

ios - 更改 NSAttributedString 文本颜色而无需再次设置标题