昨天實作完刪除資料後,今天來實作修改資料的功能
func updateItem(index: Int, value: String){
database.fetch(withRecordID: nameArray[index].recordID!) { record, error in
if record != nil && error == nil{
record?.setValue(value, forKey: "name")
self.database.save(record!) { [weak self] record, error in
if record != nil && error == nil{
print("修改成功")
self?.fetchItem()
}else{
print(error)
}
}
}else{
print(error)
}
}
上面這個function會先根據recordID去尋找該筆資料再去進行setValue並儲存結果
參數的index就是cell的indexPath.row(也對應到People陣列的index值),value是textField裡面的文字
而我們在先前令的protocol,把case "Edit"內的功能加上去
let alert = UIAlertController(title: "修改", message: "", preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = "Name"
}
let okAction = UIAlertAction(title: "確認", style: .default) { action in
self.updateItem(index: index, value: alert.textFields![0].text!)
}
let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
alert.addAction(okAction)
alert.addAction(cancelAction)
self.present(alert, animated: false, completion: nil)
就能成功修改資料至CloudKit Database啦!
如此一來CloudKit的功能大致上都實作完成了,明天會開始講新的主題,敬請期待~