我将对象添加到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)")
}
}
答案 0 :(得分:0)
将对象保存到数组
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")
}