Reputation: 2452
I'm working on a Swift 3 Realm app and I have this Realm model class:
class User: Object {
dynamic var userName = ""
dynamic var userURL = ""
dynamic var userThumbnailURL = ""
dynamic var isRegistered = false
var userID = RealmOptional<Int>()
override class func primaryKey() -> String? {
return "userID"
}
}
Then I'm adding values as follows. I'm getting them from my server and saving them in the local database:
Query 1
let user = User()
user.userName = fields["userName"] as! String
user.userURL = fields["userURL"] as! String
user.userThumbnailURL = fields["userThumbnailURL"] as! String
user.userID.value = fields["userID"] as? Int
try! uiRealm.write {
uiRealm.add(user, update: true)
}
Then when the user finishes the registration I'm updating the specific user in the local Realm database as being a registered user (isRegistered = true
). This value is only saved in the local Realm database:
uiRealm.beginWrite()
let updatingUser = uiRealm.objects(User).filter("userID = %d", self.userId)
let user = updatingUser.first
book?.isRegistered = true
try! uiRealm.commitWrite()
But my problem is that when the new server response is received and I re-run Query 1 the isRegistered
property becomes false. How can I avoid this?
Upvotes: 3
Views: 1222
Reputation: 18308
The short answer is that partial updates of an object cannot be performed by passing an instance of an Object
subclass to Realm.add(_:update:)
. The reason for this is that there's no way to represent don't update this property for a property on your Object
subclass. You'll instead want to pass a dictionary to Realm.create(_:value:update:)
, where the absence of a given key represents don't update this property.
Upvotes: 1