防止Realm在更新对象时覆盖属性 [英] Prevent Realm from overwriting a property when updating an Object
问题描述
我已经设置了REST API来实现iOS中对象的领域.但是我发现了在对象中创建收藏夹标志的问题.我创建了一个收藏夹布尔,但是每次从API更新对象时,它都会将收藏夹再次设置为默认false.在这里,我希望此标志不被更新,因为收藏夹仅存储在本地.我该如何实现?
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"
}
}
创建或更新
let pet = Pet()
pet.id = 2
pet.name = "Dog"
pet.type = "German Shephard"
try! realm.write {
realm.add(pet, update: true)
}
推荐答案
有两种解决方法:
1.使用被忽略的属性:
您可以告诉Realm某些属性不应保留.为了防止Realm保留您的favorite
属性,您必须执行以下操作:
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"]
}
}
或者您可以
2.做部分更新
或者您可以在更新Pet
对象时明确告诉Realm应该更新哪些属性:
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)
}
这样,favorite
属性将不会更改.
This way the favorite
property will not be changed.
结论
两种方法之间有一个很大的区别:
There is one big difference between the two approaches:
被忽略的属性:领域完全不会存储favorite
属性.跟踪它们是您的责任.
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.
这篇关于防止Realm在更新对象时覆盖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!