Prevent Realm from overwriting a property when updating an Object

前端 未结 3 1202
余生分开走
余生分开走 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:39

    There are two ways to solve this:

    1. Use an Ignored Property:

    You can tell Realm that a certain property should not be persisted. To prevent that your favorite property will be persisted by Realm you have to do this:

    class Pet: Object{
        dynamic var id: Int = 1
        dynamic var title: String = ""
        dynamic var type: String = ""
        dynamic var favorite: Bool = false
    
        override class func primaryKey() -> String {
            return "id"
        }
    
        override static func ignoredProperties() -> [String] {
           return ["favorite"]
       }
    }
    

    or you could

    2. Do a partial update

    Or you could tell Realm explicitly which properties should be updated when you update your Pet object:

    try! realm.write {
      realm.create(Pet.self, value: ["id": 2, "name": "Dog", "type": "German Shepard"], update: true)
    }
    

    This way the favorite property will not be changed.

    Conclusion

    There is one big difference between the two approaches:

    Ignored Property: Realm won't store the favorite property at all. It is your responsibility to keep track of them.

    Partial Update: Realm will store the 'favorite' property, but it won't be updated.

    I suppose that the partial updates are what you need for your purpose.

提交回复
热议问题