I am developing an application using Kinvey as backend. And I have an array of objects Questions
that I need to store in the database which consists of Qnumber
, Qanswer1
and Qanswer2
properties. My problem is when I try to save this array of questions in the database it always saves the last object in the array n times.
Suppose I have these data stored in the array:
Questions[0].Qnumber = 1
Questions[0].Qanswer1 = "a1"
Questions[0].Qanswer2 = "b1"
Questions[1].Qnumber = 2
Questions[1].Qanswer1 = "a2"
Questions[1].Qanswer2 = "b2"
Questions[2].Qnumber = 3
Questions[2].Qanswer1 = "a3"
Questions[2].Qanswer2 = "b3"
When I save these objects in the backend using a loop and check the database I get:
Qnumber : 3 , 3 , 3 Qanswer1 : a3, a3 , a3 Qanswer2: b3, b3, b3
I spent 2 days trying to solve this but I couldn't Here is my code:
@IBAction func saveButton(sender: AnyObject) {
let i = Int(numberOfQuestions)
var newQ : Questions = Questions()
for var index = 0; index < i; ++index {
newQ.Qnumber = String(index + 1)
newQ.Qanswer1 = cellAnswer1[index]
newQ.Qanswer2 = cellAnswer2[index]
saveObject(newQ)
}
}
func saveObject (newQuestion: Questions){
let store = KCSAppdataStore.storeWithOptions([
KCSStoreKeyCollectionName : "Questions",
KCSStoreKeyCollectionTemplateClass : Questions.self
])
store.saveObject(
newQuestion,
withCompletionBlock: { (objectsOrNil: [AnyObject]!, errorOrNil: NSError!) -> Void in
if errorOrNil != nil {
NSLog("an error happened: %@", errorOrNil)
} else {
//save was successful
NSLog("A new question is saved sucessfully")
}
},
withProgressBlock: nil
)
}
I think you should try to put the initial of newQ into the for loop
for var index = 0; index < i; ++index {
var newQ : Questions = Questions()
newQ.Qnumber = String(index + 1)
newQ.Qanswer1 = cellAnswer1[index]
newQ.Qanswer2 = cellAnswer2[index]
saveObject(newQ)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.