DCD*_*CDC 4 realm ios swift swift3
在我的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) }
}
Run Code Online (Sandbox Code Playgroud)
我只在应用程序中没有用户对象时才创建用户
由于这个答案,我以下面的方式更新我的对象
public func update(_ block: (() -> Void)) {
let realm = try! Realm()
try! realm.write(block)
}
Run Code Online (Sandbox Code Playgroud)
但事实证明它创建了新的User对象.如何始终更新现有的而不是创建新对象?
请注意我使用,User.current因为我的对象是单例
登录和注销后,它会打印用户数= 2,这意味着更新现有用户会创建一个新用户
领域将为您检查对象是否存在.只用add和update.
// Create or update the object
try? realm.write {
realm.add(self, update: true)
}
Run Code Online (Sandbox Code Playgroud)
文件:
- 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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1876 次 |
| 最近记录: |