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

时间:2017-04-20 09:09:15

标签: ios swift xcode nsuserdefaults nskeyedarchiver

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

这是数组:

// passed as parameters
int age;
string name;
bool sortByName;

var persons = _dbContext.Person;

// always filter by Age
var result = persons.Where(p => p.Age > age);

// additionally filter by Name if some condition is met
if (age > 25) {
    result = result.Where(p => p.Name == name);
}

// sort depending on parameter
if (sortByName) {
    result = result.OrderBy(p => p.Name);
}
else {
    result = result.OrderBy(p => p.Age);
}

// query will be executed when you enumerate the IQueryable
return result.ToArray();

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

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

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

然后我在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])!
        }
}