如何调用validateValue方法

Edw*_*eer 5 nscoding swift

我正在尝试制作通用的NSCoding实现,并且由于更新版本的应用程序,当对象的类型在平均时间内发生变化时会出现解码问题.

我从Swift调用validateValue方法时遇到问题.功能签名是:

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

作为参考,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)
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Edw*_*eer 1

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)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)