【问题标题】:Store data in backend using Swift使用 Swift 在后端存储数据
【发布时间】:2016-02-14 18:34:21
【问题描述】:

我正在开发一个使用 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
    )
}

【问题讨论】:

  • 假设您的 Questions 对象是一个集合类型,您是否尝试过将对 saveObjext(newQ) 的调用移到循环之外?我敢打赌,它会节省三倍,因为您的 count 属性是 3,并且您的循环在每个问题上运行 3 次。
  • 或者将 newQ 属性移到循环内

标签: ios iphone database swift kinvey


【解决方案1】:

我认为您应该尝试将 newQ 的首字母放入 for 循环中

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)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多