如何调用 validateValue 方法

How to call the validateValue method

我正在尝试制作一个通用的 NSCoding 实现,但是当对象的类型同时由于应用程序的更新版本而发生变化时,我遇到了解码问题。

我在从 Swift 调用 validateValue 方法时遇到问题。函数签名是:

func validateValue(_ ioValue: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: String, error outError: NSErrorPointer) -> Bool

作为参考,可以在此处找到 Apple 文档:NSCoding validateValue

我要创建的代码是:

public class func decodeObjectWithCoder(theObject:NSObject, aDecoder: NSCoder) {
        for (key, value) in toDictionary(theObject) {
            if aDecoder.containsValueForKey(key) {
                let newValue: AnyObject? = aDecoder.decodeObjectForKey(key)
                NSLog("set key \(key) with value \(newValue)")
                var error:NSError?

                var y:Bool = theObject.validateValue(newValue, forKey: key, error: &error)
                if y {
                    theObject.setValue(newValue, forKey: key)
                }
            }
        }
    }

我无法正确调用 .validateValue。我不断收到编译错误。我该怎么称呼它。 toDictionary 函数可以在以下位置找到:EVReflection

更新:我刚刚发现这段代码可以编译:

        var ioValue: AutoreleasingUnsafeMutablePointer<AnyObject?> = nil
        var y:Bool = theObject.validateValue(ioValue, forKey: key, error: nil)

这意味着 AnyObject 类型的值?无法转换为 AutoreleasingUnsafeMutablePointer

newValue 字段必须通过在其前面添加 & 作为指针传递。除此之外,你必须使用 var 而不是 let。所以最终代码将是:

public class func decodeObjectWithCoder(theObject:NSObject, aDecoder: NSCoder) {
    for (key, value) in toDictionary(theObject) {
        if aDecoder.containsValueForKey(key) {
            var newValue: AnyObject? = aDecoder.decodeObjectForKey(key)
            if theObject.validateValue(&newValue, forKey: key, error: nil) {
                theObject.setValue(newValue, forKey: key)
            }
        }
    }
}