已弃用archiveRootObject(_to:file :),不确定如何实现新编码

时间:2019-01-22 00:11:54

标签: swift xcode nscoding

我正在尝试使用NSCoding保存数据,但被告知我正在尝试使用的命令在iOS 12中已被弃用,并且我迷失了试图解决如何实现Xcode建议使用的编码的问题采用。我确定问题已经提出并得到了回答,但是我迷失了寻找答案的方法。我将不胜感激。

编码:

func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: PropertyKey.characterName)
    aCoder.encode(race, forKey: PropertyKey.characterRace)
    aCoder.encode(cclass, forKey: PropertyKey.characterClass)
    aCoder.encode(background, forKey: PropertyKey.characterBackground)
    aCoder.encode(photo, forKey: PropertyKey.characterPhoto)
}

required convenience init?(coder aDecoder: NSCoder) {
    guard let name = aDecoder.decodeObject(forKey: PropertyKey.characterName) as? String else {
        os_log("Unable to decode the name for a character object.", log: OSLog.default, type: .debug)
        return nil
    }
    let race = aDecoder.decodeObject(forKey: PropertyKey.characterRace) as? String
    let cclass = aDecoder.decodeObject(forKey: PropertyKey.characterClass) as? String
    let background = aDecoder.decodeObject(forKey: PropertyKey.characterBackground) as? String
    let photo = aDecoder.decodeObject(forKey: PropertyKey.characterPhoto) as? UIImage

    self.init(name: name, race: race ?? "", cclass: cclass ?? "", background: background ?? "", photo: photo)
}

保存编码:

private func saveCharacters() {

    let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(characterList, toFile: Character.ArchiveURL.path)
    if isSuccessfulSave {
        os_log("Characters successfully saved", log: OSLog.default, type: .debug)
    } else {
        os_log("Failed to save Characters", log: OSLog.default, type: .error)
    }
}

Xcode建议我使用+ archivedDataWithRootObject:requiringSecureCoding:error:但我无法解决如何实现此问题。

0 个答案:

没有答案