Swift:将具有另一个对象数组的对象数组保存到NSUserDefaults中

问题描述 投票:1回答:1

我一直在工作,虽然我的第一个应用程序,但我需要保存用户数据,但不能。我有一个对象数组,里面也有一个“Questions”对象数组:

struct Question {
    let question: String
    let answer: String
}

struct UserEntry {
    let date: String
    let questions: [Question]
}

let userEntry = [UserEntries(date: todayDate, questions: [Question(answer: mood), Question(question: q1Text, answer: q1Answer), Question(question: q2Text, answer: q2Answer)])]

但是,这是抛出错误:无法将“ThisViewController.Question”类型的值转换为预期的元素类型“UserEntries.Question”。接下来的另一个堆栈答案也为它创建了一个类:

class UserEntries: NSObject, NSCoding {
struct Question {
    var question: String
    var answer: String
}

var date: String
var questions: [Question]

init(date: String, questions: [Question]) {
    self.date = date
    self.questions = questions
}

required convenience init(coder aDecoder: NSCoder) {
    let date = aDecoder.decodeObject(forKey: "date") as! String
    let question = aDecoder.decodeObject(forKey: "questions")
    self.init(date: date, questions: question as! [UserEntries.Question])
}

func encode(with aCoder: NSCoder) {
    aCoder.encode(date, forKey: "date")
    aCoder.encode(questions, forKey: "questions")
}
}

我正在保存这样的数据:

let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: userEntry)
UserDefaults.standard.set(encodedData, forKey: "allEntries")

我对错误感到困惑,非常感谢任何帮助或指导!

ios swift object nsuserdefaults
1个回答
0
投票

你的问题是你在两个地方创建了Question对象。

看一下错误信息:

无法将“ThisViewController.Question”类型的值转换为预期的元素类型“UserEntries.Question”。

现在看看你提供的代码,首先我想是来自YourViewController

struct Question {
    let question: String
    let answer: String
}

struct UserEntry {
    let date: String
    let questions: [Question]
}

let userEntry = [UserEntries(date: todayDate, questions: [Question(answer: mood), Question(question: q1Text, answer: q1Answer), Question(question: q2Text, answer: q2Answer)])]

然后:

class UserEntries: NSObject, NSCoding {
struct Question {
    var question: String
    var answer: String
}
...

所以......你在Question中定义了ThisViewController然后你在Question类中定义了另一个UserEntries

编译器告诉你它认为你使用的是ThisViewController.Question,你无法添加到UserEntries.Question,因为这些是编译器的两个不同的东西。

当你将QuestionUserEntry逻辑移动到符合UserEntriesNSCoding类时,你也不再需要它在YourViewController中。

所以,从你的Question删除UserEntryYourViewController结构,这样你在Question只有一个UserEntries,事情应该(希望)再次起作用。

希望有所帮助。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.