如何保存可以随时访问的数据数组?

时间:2019-01-15 00:02:33

标签: arrays swift core-data nsuserdefaults

我有一个已经开始开发的简单测验应用程序,如果强制退出并重新打开该应用程序,我想保存用户进度。

我有一个名为“问题”的类,该类由变量Strings和一个名为“ Film”的枚举组成,具有三种情况。我创建了问题,然后将这些问题添加到数组中。

在我的代码本身中,我确保一旦提出问题,该问题就会从我的“ allQuestions”数组中取出,然后添加到一个名为“ usedQuestions”的新数组中。

我想做的就是保存我的“ usedQuestions”数组,然后能够在应用程序加载时和加载时加载这些问题。

我已经探索了使用UserDefaults的方法,但是看起来这是不可能的,并且我也研究了使用CoreData的方法,但是目前正在努力使它也能正常工作。

//Class: 
class Question {

    var questionBody: String
    var correctAnswer: String
    var wrongAnswer: String
    var wrongAnswerTwo: String
    var wrongAnswerThree: String
    let filmTitle: Film

    enum Film {
         case one, two, three
    }

let firstQuestion = Question(questionBody: "This is question one", correctAnswer: "Correct", wrongAnswer: "Wrong Answer", wrongAnswerTwo: "Wrong Answer Two", wrongAnswerThree: "Wrong Answer Three", filmTitle: ".one"
let secondQuestion = Question(questionBody: "This is question Two", correctAnswer: "Correct", wrongAnswer: "Wrong Answer", wrongAnswerTwo: "Wrong Answer Two", wrongAnswerThree: "Wrong Answer Three", filmTitle: ".two"
let thirdQuestion = Question(questionBody: "This is question Three", correctAnswer: "Correct", wrongAnswer: "Wrong Answer", wrongAnswerTwo: "Wrong Answer Two", wrongAnswerThree: "Wrong Answer Three", filmTitle: ".three"

let allQuestions = [firstQuestion, secondQuestion, thirdQuestion]

//Code: 
var usedQuestions = [Question]()
var storedQuestion = Question(questionBody: "", correctAnswer: "", wrongAnswer: "", wrongAnswerTwo: "", wrongAnswerThree: "", filmTitle: .one)

func saveQuestionAsked(storedQuestion: Question) {
        let savedQuestion = storedQuestion
        usedQuestions.insert(savedQuestion, at: 0)
    }

let chosenQuestion = Int(arc4random_uniform(UInt32(allQuestions.count)))
storedQuestion = allQuestions[chosenQuestion]
saveQuestionAsked(storedQuestion: allQuestions[chosenQuestion])
allQuestions.remove(at: chosenQuestion)

使用上面的代码,我从“ allQuestions”数组中删除了“ storedQuestion”,然后将其插入“ usedQuestion”数组中。

我现在希望能够将问题保存在该数组中,以便当用户返回时,这些问题仍然存在于该数组中。

1 个答案:

答案 0 :(得分:0)

如果您要使用Core Data,则可能需要进行以下设置:

当我最初了解Core Data时,我使用了此资源(您可能会通过一些研究找到更好的方法):This one right here

基本上,创建一个PersistenceManager类,该类将允许您保存和获取Core Data对象。

然后创建一个将数据保存到核心数据的功能。

class PersistenceManager {

    private init() {}

    static let shared = PersistenceManager()
    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: "NAME_OF_COREDATA_THING")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    lazy var context = persistentContainer.viewContext
    func save() {
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

    func fetch<T: NSManagedObject>(objectType: T.Type) -> [T] {
        let entityName = String(describing: objectType)
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        do {
            let fetchedObjects = try context.fetch(fetchRequest) as? [T]
            return fetchedObjects ?? [T]()
        } catch {
            return [T]()
        }
    }
}



func saveToCoreData(storedQuestionArray: [Question]) {
    for node in storedQuestionArray {
        let master = Master(context: PersistenceManager.shared.context)
        master.questionBody = node.questionBody
        master.correctAnswer = node.correctAnswer
        master.wrongAnswer = node.wrongAnswer
        master.wrongAnswerTwo = node.wrongAnswerTwo
        master.wrongAnswerThree = node.wrongAnswerThree
        master.filmTitle = node.filmTitle
        PersistenceManager.shared.save()
    }
}