Search code examples
iosswiftrealm

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


Instead of saving data how to update the same object when we didSelectRowAt.

Like offerName "Diwali" to "oct" to without creating new object "diwali" should change to "oct".

How can i do that?

Program :-

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

Solution

  • Examples below are written with a help of a Realm swift documentation

    There are two ways to update objets in realm.

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