2017-04-20 64 views
0

我有一个包含多个问题的数组,并且一旦它显示问题,它就会从索引中删除它而不会再显示。问题是一旦应用程序重新启动它不会保存这个。我需要能够保存它,因此它不显示已经显示的问题。将自定义数组保存到用户默认设置

这里是数组:

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) 
    } 
} 

感谢。

+0

检查答案这个问题:http://stackoverflow.com/questions/25179668/how-to-save-and-read-array-of-array-in-nsuserdefaults-in-swift。 –

+0

如何将你的数组添加到userdefault中? – KKRocks

+0

你需要使用密钥存档器来存储这种数据在NSUser默认 – KavyaKavita

回答

0

找到答案在Apple Developer Website,然后转换成迅速。

首先我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") 

然后我检索它在viewDidLoad中与NSKeyedUnarchiver解除存档它,然后得到它从UserDefaults:

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

更好的做法是存储当前问题索引,而不是删除数组的元素。将索引存储在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 
+0

如何将此索引链接到数组? – Username

+0

//问题是一个包含对象的数组 let q1 = questions [index]; let questionLabel = q1.question; –

相关问题