无法将类型数据转换为预期类型数据

时间:2018-04-04 02:27:00

标签: ios swift nsuserdefaults

在将自定义类保存并加载到UserDefaults时,我遇到了一些问题。问题是上面提到的,当我从UserDefaults加载一些被绑定的数据并尝试使用NSKeyedUnarchiver解码它时,它告诉我"无法转换类型'数据'的值预期参数类型'数据' &#34 ;.我已经尝试了各种各样的东西,但这个错误没有意义。

tatic func saveGrupo(data: [Grupo]) {
    let encodedData = NSKeyedArchiver.archivedData(withRootObject: data)
    UserDefaults.standard.set(encodedData, forKey: Grupo.key)
}

static func loadGrupo() -> [Grupo]? {
    let decoded  = UserDefaults.standard.object(forKey: Grupo.key) as! Data
    return NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Grupo]
}

这是我的保存和加载代码。

这是我的班级声明,以防这里出现问题:

class Grupo: NSObject, NSCoding, Decodable {

//MARK: Properties

let id: Int
let name: String

static let key = "groups"

//MARK: Archiving Paths

static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("Groups")

//MARK: Types

struct PropertyKey {
    static let id = "id"
    static let name = "name"
}

//MARK: Initializer

init(id: Int,name: String) {

    self.id = id
    self.name = name

}

//MARK: NSCoding

func encode(with aCoder: NSCoder) {
    aCoder.encode(id, forKey: PropertyKey.id)
    aCoder.encode(name, forKey: PropertyKey.name)
}

required convenience init?(coder aDecoder: NSCoder) {

    guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {
        return nil
    }

    let id = aDecoder.decodeInteger(forKey: PropertyKey.id)

    self.init(id: id,name: name)
}

}

0 个答案:

没有答案