Prevent Realm from overwriting a property when updating an Object

前端 未结 3 1200
余生分开走
余生分开走 2021-02-05 04:54

I\'ve setup a REST API to realm object in iOS. However I\'ve found an issue with creating a favorite flag in my object. I\'ve created a favorite bool, however everytime the obje

3条回答
  •  终归单人心
    2021-02-05 05:41

    If you want to be more explicit, there is third option:

    3. Retrieve the current value for the update

    // Using the add/update method
    let pet = Pet()
    pet.id = 2
    pet.name = "Dog"
    pet.type = "German Shephard"
    
    if let currentObject = realm.object(ofType: Pet.self, forPrimaryKey: 2) {
        pet.favorite = currentObject.favorite
    }
    
    try! realm.write {
        realm.add(pet, update: true)
    }
    
    // Using the create/update method
    var favorite = false
    if let currentObject = realm.object(ofType: Pet.self, forPrimaryKey: 2) {
        favorite = currentObject.favorite
    }
    
    // Other properties on the pet, such as a list will remain unchanged
    try! realm.write {
        realm.create(Pet.self, value: ["id": 2, "name": "Dog", "type": "German Shephard", "favorite": favorite], update: true)
    }
    

提交回复
热议问题