尝试将结构数组保存到UserDeafults时出错

时间:2016-11-13 18:47:54

标签: arrays swift struct swift3 nsuserdefaults

在网站上的另一篇文章中找到此示例代码

struct Foo {
    var a : String
    var b : String?
}

extension Foo {
    init?(data: NSData) {
        if let coding = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Encoding {
            a = coding.a as String
            b = coding.b as String?
        } else {
            return nil
        }
    }

    func encode() -> NSData {
        return NSKeyedArchiver.archivedData(withRootObject: Encoding(self)) as NSData
    }

    private class Encoding: NSObject, NSCoding {    //Here is the error
        let a : NSString
        let b : NSString?

        init(_ foo: Foo) {
            a = foo.a as NSString
            b = foo.b as NSString?
        }

        @objc required init?(coder aDecoder: NSCoder) {
            if let a = aDecoder.decodeObject(forKey: "a") as? NSString {
                self.a = a
            } else {
                return nil
            }
            b = aDecoder.decodeObject(forKey: "b") as? NSString
        }

        @objc func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encode(a, forKey: "a")
            aCoder.encode(b, forKey: "b")
        }

    }
}

我试图弄清楚它是如何工作的,但它有以下错误:type 'Foo.Encoding' does not conform to protocol 'NSCoding'。我不知道这是从swift到swift 3的变化,但是没有像其他行那样自动修复它。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

根据documentation,实施NSCoding协议的类必须包含init?(coder: NSCoder)encode(with: NSCoder)方法。

在您的代码中,我看到encodeWithCoder(aCoder: NSCoder)。将其更改为encode(with: NSCoder),代码可以正常运行。