在Swift 4中取消归档NSMutableArray

时间:2018-02-24 16:57:03

标签: swift nsmutablearray nsuserdefaults

我将对象添加到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)")
    }
}

1 个答案:

答案 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")
        }