2017-04-20 60 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; –

相關問題