我有下面的代码。它已经被反对,并给我黄色的警告。我想让它消失。对如何解决这个问题有什么想法吗?
var linearScore = 0
var spreadScore = 0
func saveScores () {
print("SAVE START")
let scores : [Int] = [linearScore, spreadScore]
let encodedData = NSKeyedArchiver.archivedData(withRootObject: scores)
UserDefaults.standard.set(encodedData, forKey: "scores")
}
func retrieveScores () {
print("Scores being retrieved")
//comment out the if/let below to reset goals in dev
if let data = UserDefaults.standard.data(forKey: "scores"),
let scoreList = NSKeyedUnarchiver.unarchiveObject(with: data) as? [Int] {
self.linearScore = scoreList[0]
self.spreadScore = scoreList[1]
self.updateTopScores()
} else {
print("There is an issue")
self.saveScores()
}
}带有此错误的不推荐代码如下2行:
设encodedData = NSKeyedArchiver.archivedData(withRootObject:分数)
设scoreList =NSKeyedUnarchiver.unarchiveObject(有: data)作为?Int {
发布于 2019-07-19 17:05:56
您需要使用新的存档和解压缩方法。首先,让您的方法抛出并使用以下方法进行归档:
class func archivedData(withRootObject object: Any, requiringSecureCoding requiresSecureCoding: Bool) throws -> Data这是为了公开档案:
class func unarchiveTopLevelObjectWithData(_ data: Data) throws -> Any?就像这样:
func saveScores() throws {
print(#function)
let scores = [linearScore, spreadScore]
let encodedData = try NSKeyedArchiver.archivedData(withRootObject: scores, requiringSecureCoding: false)
UserDefaults.standard.set(encodedData, forKey: "scores")
}
func retrieveScores() throws {
print(#function)
if let data = UserDefaults.standard.data(forKey: "scores"),
let scoreList = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [Int] {
} else {
print("There is an issue")
self.saveScores()
}
}请注意,您也可以使用可编码协议来编码/解码自Swift 4以来的模型数据。
var linearScore = 2
var spreadScore = 7
func saveScores() throws {
print(#function)
let scores = [linearScore, spreadScore]
let encodedData = try JSONEncoder().encode(scores)
UserDefaults.standard.set(encodedData, forKey: "scores")
print("scores saved")
}
func retrieveScored() throws {
print(#function)
if let data = UserDefaults.standard.data(forKey: "scores") {
let scoreList = try JSONDecoder().decode([Int].self, from: data)
print("scoreList:", scoreList)
} else {
print("No data found in user defaults for scores")
}
}如果您不想抛出错误,只需根据需要使用do、try、catch:
func saveScores() {
print(#function)
let scores = [linearScore, spreadScore]
do {
try UserDefaults.standard.set(JSONEncoder().encode(scores), forKey: "scores")
print("scores saved")
} catch {
print(error)
}
}
func retrieveScores() {
print(#function)
if let data = UserDefaults.standard.data(forKey: "scores") {
do {
let scoreList = try JSONDecoder().decode([Int].self, from: data)
print("scoreList:", scoreList)
} catch {
print(error)
}
} else {
print("No data found in user defaults for scores")
}
}https://stackoverflow.com/questions/57116638
复制相似问题