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 object is updated from the API it sets the favorite to default false again. Here I want this flag to not be updated, since the favorite only is stored locally. How can I achieve 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" } }
CreateOrUpdate
let pet = Pet() pet.id = 2 pet.name = "Dog" pet.type = "German Shephard" try! realm.write { realm.add(pet, update: true) }
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With