我正在将对象添加到NSMutableArray中,并使用NSKeyedArchiver和UserDefaults对其进行归档。
对象被添加到数组中,我可以从日志控制台看到它。我还可以看到归档对象包含该对象。
问题是,每当我解压缩对象并将它们添加到可变数组中时,它总是返回1,不管我添加了多少个对象。
我得到的是:
将对象保存到数组
trackNumberOfQuestionPlayed.add(questionsArray[randomQuestion] as AnyObject)
let saveQuestionsPlayed = NSKeyedArchiver.archivedData(withRootObject: trackNumberOfQuestionPlayed)
UserDefaults.standard.set(saveQuestionsPlayed, forKey: "QuestionsPlayed")
UserDefaults.standard.synchronize()
print(UserDefaults.standard.object(forKey: "QuestionsPlayed"))检索对象
if let data = UserDefaults.standard.object(forKey: "QuestionsPlayed") as? Data {
if let trackNumberOfQuestionPlayed = (NSKeyedUnarchiver.unarchiveObject(with: data) as? NSMutableArray)
{
// In here you can access your array
print("Number of questions array is NOT empty: \(trackNumberOfQuestionPlayed.count)")
}
}发布于 2018-02-26 19:02:20
好吧,我在回答我自己的问题。结果是,只要稍微调整一下,就可以像我的问题中所描述的那样保存一个数组。结果是我的智力测验游戏中的其他代码把这一切搞得一团糟。把它整理出来,下面的代码开始工作了:
将对象保存到数组
trackNumberOfQuestionPlayed.add(questionsArray[randomQuestion] as AnyObject)
let saveQuestionsPlayed = NSKeyedArchiver.archivedData(withRootObject: trackNumberOfQuestionPlayed)
UserDefaults.standard.set(saveQuestionsPlayed, forKey: "QuestionsPlayed")
UserDefaults.standard.synchronize()
print("Count: \(trackNumberOfQuestionPlayed.count)")检索对象
if let data = UserDefaults.standard.object(forKey: "QuestionsPlayed") as? Data {
if let trackNumberOfQuestionPlayed = (NSKeyedUnarchiver.unarchiveObject(with: data) as? NSMutableArray)
{
// In here you can access your array
self.trackNumberOfQuestionPlayed = trackNumberOfQuestionPlayed
print("Number of questions array is NOT empty: \(trackNumberOfQuestionPlayed.count)")
}
} else {
trackNumberOfQuestionPlayed = NSMutableArray()
print("questionsplayed is empty")
}https://stackoverflow.com/questions/48965285
复制相似问题