将自定义数组保存为用户默认值

Saving Custom Array To User Defaults

我有一个包含多个问题的数组,一旦它显示了问题,它就会将其从索引中删除,不再显示。问题是一旦应用程序重新启动,它就不会保存它。我需要能够保存它,这样它就不会显示已经显示的问题。

这是数组:

questions = [question(question: "The Average Adult Human Body Contains 206 Bones", answers:["True","False"], answer: 0),
                 question(question: "Bees Have One Pair Of Wings", answers: ["True", "False"], answer: 1),
                 question(question: "The Shanghi Tower Is The Tallest Building In The World", answers: ["True", "False"], answer: 1),
                 question(question: "1024 Bytes Is Equal To 10 Kilobytes", answers: ["True", "False"], answer: 1)].....Plus More

这是我选择然后删除问题的地方:

func pickQuestion() {
    if questions.count > 0 {
        questionNumber = Int(arc4random_uniform(UInt32(questions.count)))
        questionLabel.text = questions[questionNumber].question
        answerNumber = questions[questionNumber].answer

        for i in 0..<trueorfalse.count {
            trueorfalse[i].setTitle(questions[questionNumber].answers[i], for: UIControlState.normal)
        }
        //Here is where the question is removed from the array.
        questions.remove(at: questionNumber)
    }
}

谢谢。

更好的做法是存储当前问题索引而不是删除数组的元素。将索引存储在 UserDefaults 中,然后检索它并在用户下次启动您的应用程序时使用它。

示例:

UserDefaults.standard.set(index, forKey: "saved_index")

每次向用户显示新问题时都会发生这种情况。

当用户重新启动应用程序并且您想显示他已停止的问题时,您将使用:

let index = UserDefaults.standard.integer(forKey: "saved_index")

用法:

//questions is an Array with objects 
let q1 = questions[index]
let questionLabel = q1.question

Apple Developer Website 找到答案,然后转换为 swift。

首先我使用 NSKeyedArchiver 将其存档,然后将其保存到 UserDefaults:

questions.remove(at: questionNumber)
//Archiving Custom Object Array Into NSKeyedArchiver And Then Saving NSData To UserDefaults
let theData = NSKeyedArchiver.archivedData(withRootObject: questions)
UserDefaults.standard.set(theData, forKey: "questionData")

然后我通过使用 NSKeyedUnarchiver 取消存档在 viewDidLoad 中检索它,然后从 UserDefaults 中获取它:

override func viewDidLoad() {
        super.viewDidLoad()
        let theData: Data? = UserDefaults.standard.data(forKey: "questionData")
        if theData != nil {
            questions = (NSKeyedUnarchiver.unarchiveObject(with: theData!) as? [question])!
        }
}