在iOS 12.1中,不推荐使用unarchiveObject(withFile:)
如何转换NSKeyedUnarchiver.unarchiveObject(withFile: String)以使用对NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data: Data)NSKeyedUnarchiver.unarchivedObject(ofClasses: [AnyClass]的调用,该调用来自:Data)或NSKeyedUnarchiver.unarchivedObject(ofClass: NSCoding.Protocol, from: Data)

我猜您必须拥有类似let fileData = try Data(contentsOf: URL)的内容,然后使用这些方法之一来取消存档数据。但是,我无法弄清楚,折旧随附的文档没有帮助(至少对我而言)。

存档的数据非常简单-只是一个字符串数组(此代码定义的NameToBeSaved类的数组):

class NameToBeSaved: NSObject, NSCoding {
var name: String

init(userEnteredName: String) {
    self.name = userEnteredName
    super.init()
}

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

required init?(coder aDecoder: NSCoder) {
    name = aDecoder.decodeObject(forKey: "name") as! String
    super.init()
}

这是调用unarchiveObject(withFile :)的代码-
init() {
    if let archivedCategoryNames = NSKeyedUnarchiver.unarchiveObject(withFile: categoryNameArchiveURL.path) as? [NameToBeSaved] {
        allCategories += archivedCategoryNames
    } else {
        for category in starterCategories {
            let thisNewCategory = NameToBeSaved(userEnteredName: category)
            createNewCategory(thisNewCategory)
        }
        sortCategories()
    }
}

最佳答案

我不知道这是否是最好的解决方案,但这对我来说解决了转换(旧代码已注释掉以便进行比较):

    init() {

    do {
        let rawdata = try Data(contentsOf: categoryNameArchiveURL)
        if let archivedCategoryNames = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(rawdata) as! [NameToBeSaved]? {
            allCategories += archivedCategoryNames
        }
    } catch {
        print("Couldn't read file")
        for category in starterCategories {
            let thisNewCategory = NameToBeSaved(userEnteredName: category)
            createNewCategory(thisNewCategory)
        }
        sortCategories()
    }

/*        if let archivedCategoryNames = NSKeyedUnarchiver.unarchiveObject(withFile: categoryNameArchiveURL.path) as? [NameToBeSaved] {
            allCategories += archivedCategoryNames
        } else {
            for category in starterCategories {
                let thisNewCategory = NameToBeSaved(userEnteredName: category)
                createNewCategory(thisNewCategory)
            }
            sortCategories()
        }
 */
}

关于ios - 如何解决unarchiveObject(withFile :)的弃用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53097261/

10-12 00:30
查看更多