Save multiply objects from array in core data

时间:2015-07-28 16:55:36

标签: swift core-data

I have an array, which contains 3 questions. Each question has several properties. I want to iteratively store all the questions in core data.

here with what i came with

 func saveToDb() {

        var appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        var managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!

        let entity = NSEntityDescription.entityForName("QuestionDB", inManagedObjectContext: managedContext)
        let question = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)


        for var i = 0; i < storage.count; ++i {
            question.setValue(self.storage[i]?.questionText, forKey: "questionText")
            question.setValue(self.storage[i]?.answer1, forKey: "answer1")
            question.setValue(self.storage[i]?.answer2, forKey: "answer2")
            question.setValue(self.storage[i]?.answer3, forKey: "answer3")
            question.setValue(self.storage[i]?.answer4, forKey: "answer4")
            question.setValue(self.storage[i]?.correctAnswer, forKey: "correctAnswer")

    }

        managedContext.save(nil)
        println(question)

but this code saves only last item in array storage

i tried to use the code

newQuestion = question(entity:entity, insertIntoManagedObjectContext: context) 
....
map the fields here

but xcode complains about this string that it don't match the init method for class question

how to solve the task correctly ?

1 个答案:

答案 0 :(得分:2)

Declare the question and managedContext.save(nil) inside of your for loop