swift - 如何调用 validateValue 方法

标签 swift nscoding

我正在尝试制作一个通用的 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)
            }
        }
    }
}

关于swift - 如何调用 validateValue 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28181571/

相关文章:

cocoa-touch - NSKeyedArchiver unarchiveObjectWithFile 因 EXC_BAD_INSTRUCTION 而崩溃

xcode - swift 错误 : EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, 子代码 = 0x0)

ios - ARSCNView 截图

macos - 没有 Storyboard或使用 Swift 的 xib 文件的 OSX 应用程序

ios - initWithCoder : function is not called from unarchiveObjectWithData:

ios - 如果模型对象文件有很多依赖项,如何将其导入到我的 watch 扩展中

swift - 后台 URLSession + Combine?

ios - 在 Swift 中找到最近的 UIView 的最佳方法

ios - 如何使用 Swift 保存(持久化)包含其他类的类对象

arrays - Swift NSCoding - 如何读取编码数组