Swift 3: Realm creates additional object instead o

2019-06-28 08:37发布

In my AppDelegate

let realm = try! Realm()
    print("number of users")
    print(realm.objects(User.self).count)
    if !realm.objects(User.self).isEmpty{
        if realm.objects(User.self).first!.isLogged {
            User.current.setFromRealm(user: realm.objects(User.self).first!)
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let viewController = storyboard.instantiateViewController(withIdentifier :"TabBar") as! CustomTabBarController
            self.window?.rootViewController = viewController
        }
    } else {
        try! realm.write { realm.add(User.current) }
    }

I create user only when there are no user objects across the app

thanks to this answer I update my object in the following way

public func update(_ block: (() -> Void)) {
    let realm = try! Realm()
    try! realm.write(block)
}

But it turns out it creates new User object. How to always update the already existing one instead of creating new object?

Note that I use User.current since my object is a singleton

After I login and logout, it prints number of users = 2, which means that updating already existing user creates a new one

2条回答
Viruses.
2楼-- · 2019-06-28 08:58

Realm will check if the object exist or not for you. Only use add and update.

// Create or update the object
try? realm.write {
   realm.add(self, update: true)
}     

Documentation :

 - parameter object: The object to be added to this Realm.
 - parameter update: If `true`, the Realm will try to find an existing copy of the object (with the same primary
                     key), and update it. Otherwise, the object will be added.
查看更多
淡お忘
3楼-- · 2019-06-28 09:00

realm.write is incapable of adding new objects, unless you're calling realm.add inside of it. If you're getting 2 objects in the database, it either means that your logic for checking if the object already exists is failing, or the logic for deleting the previous object when logging out is failing.

Calling realm.add on the same object twice will not add 2 copies to the database, so it could also indicate you're creating 2 unmanaged User objects in your logic as well.

In any case, I'd recommend double-checking your logic to absolutely ensure you're not adding two objects to Realm by accident.

let realm = try! Realm()
let firstUser = realm.objects(User.self).first

if let firstUser = firstUser {
    User.current.setFromRealm(user: firstUser)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = storyboard.instantiateViewController(withIdentifier :"TabBar") as! CustomTabBarController
    self.window?.rootViewController = viewController
}
else {
    try! realm.write { realm.add(User.current) }
}
查看更多
登录 后发表回答