Swift 3:Realm创build额外的对象,而不是更新现有的对象

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

我只在应用程序中没有用户对象时才创build用户

感谢这个答案我以下面的方式更新我的对象

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

但事实certificate它创build了新的用户对象。 如何总是更新已经存在的而不是创build新的对象?

请注意,我使用User.current因为我的对象是一个单身人士

login和注销后,它打印的用户数= 2,这意味着更新已经存在的用户创build一个新的

realm.write不能添加新的对象,除非你在里面调用realm.add 。 如果您在数据库中获取2个对象,则表示您检查对象是否已经存在的逻辑失败,或者注销时删除前一个对象的逻辑失败。

在同一对象上调用realm.add两次不会将两个副本添加到数据库,因此也可能表明您在逻辑中也创build了2个非托pipeUser对象。

无论如何,我build议仔细检查一下你的逻辑,以确保你不会意外地把两个对象添加到Realm中。

 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) } } 

领域将检查对象是否存在与否。 只能使用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.