示例工程 26-objc-cpp-interop

26-objc-cpp-interop/Sources/Ch26Kit/ObjCBridge.swift

swift · 1.5 KB

import Foundation
 
/// `@objc dynamic` 属性可被 KVO 观察;消息派发让 Objective-C 运行时能看到它。
public final class SettingsModel: NSObject {
    @objc dynamic public var theme: String = "light"
 
    @objc public func describe() -> String {
        "theme=\(theme)"
    }
}
 
/// KVO 回调可能在任意线程执行,用锁保护记录。
public final class ChangeRecorder: @unchecked Sendable {
    private let lock = NSLock()
    private var storage: [String] = []
 
    public init() {}
 
    public var values: [String] {
        lock.lock()
        defer { lock.unlock() }
        return storage
    }
 
    public func record(_ value: String) {
        lock.lock()
        storage.append(value)
        lock.unlock()
    }
}
 
public enum ObjectiveCLab {
    public static func observeTheme() -> [String] {
        let model = SettingsModel()
        let recorder = ChangeRecorder()
        let observation = model.observe(\.theme, options: [.new]) { _, change in
            if let value = change.newValue {
                recorder.record(value)
            }
        }
        model.theme = "dark"
        model.theme = "blue"
        observation.invalidate()
        return recorder.values
    }
 
    public static func respondsToDescribe() -> Bool {
        let model = SettingsModel()
        return model.responds(to: #selector(SettingsModel.describe))
    }
 
    public static func callDescribe() -> String {
        let model = SettingsModel()
        return model.describe()
    }
}