使用领域我如何更新数据,它不应该创建新对象只更新对象

Using realm how can i update data,It should not create new object only update object

当我们执行 SelectRowAt 时如何更新同一个对象而不是保存数据。

喜欢 offerName "Diwali" 到 "oct" 到不创建新对象 "diwali" 应该更改为 "oct"。

我该怎么做?

程序:-

let newArray = Discount()
 newArray.offerName = offerName.text!

               let percent = Float(offerValue.text!)
               newArray.segmentIndex = segment.selectedSegmentIndex
              newArray.percentage = percent!


                  //This will go to Create data and save
                   self.saveItems(category: newArray)

                    self.navigationController?.popViewController(animated: true)

}    

func saveItems(category: Discount) {
           do{

               try realm.write {//Save/Create
                   realm.add(category)
               }               
           }catch {
               print("Error in saving \(error)")
           }
       }

下次遇到此类问题时,请尝试先查看领域文档,如果找不到答案,请在堆栈溢出时询问。阅读文档对于成为更好的程序员很重要。这是领域文档的 link:Realm swift documentation

有两种方法可以更新领域中的对象。

The first option is better for updating single object

var yourObject = Object()

do {
  try realm.write {
    yourObject.property = "Some new value"
  }
} catch {
  print("Unable to update object.")
}

The second option is better for updating collection of objects

var arrayOfImageObjects = realm.objects(Image.self)

do {
  try realm.write {
    // Update first item in array
    // Here we're updating isNewImage property and setting it to false
    arrayOfImageObjects.first!.setValue(false, forKeyPath: "isNewImage")

    // Update all images
    // Here we're updating isNewImage property of all images in array and setting it to false
    arrayOfImageObjects.setValue(false, forKeyPath: "isNewImage")
  }
} catch {
  print("Unable to update objets.")
}