草庐IT

ios - swift 3 : Realm creates additional object instead of updating the exisiting one

coder 2023-09-06 原文

在我的 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) }
    }

我只在整个应用中没有用户对象时才创建用户

多亏了这个answer我按以下方式更新我的对象

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

但事实证明它创建了新的用户对象。如何始终更新已经存在的对象而不是创建新对象?

请注意,我使用 User.current 因为我的对象是单例

在我登录和注销后,它打印用户数 = 2,这意味着更新现有用户会创建一个新用户

最佳答案

Realm 会为你检查对象是否存在。仅使用addupdate

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

文档:

 - 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.

关于ios - swift 3 : Realm creates additional object instead of updating the exisiting one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41933447/

有关ios - swift 3 : Realm creates additional object instead of updating the exisiting one的更多相关文章

随机推荐