我正在开发一个使用 Kinvey 作为后端的应用程序。我有一组对象Questions
,我需要存储在数据库中,其中包括Qnumber
和Qanswer1
属性Qanswer2
。我的问题是当我尝试将这一系列问题保存在数据库中时,它总是将最后一个对象保存在数组中 n 次。
假设我将这些数据存储在数组中:
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"
当我使用循环将这些对象保存在后端并检查数据库时,我得到:
Qnumber : 3 , 3 , 3 Qanswer1 : a3, a3 , a3 Qanswer2: b3, b3, b3
我花了 2 天时间试图解决这个问题,但我不能这是我的代码:
@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
)
}