当用户登录时,我创建了一个Person对象:
let creds = SyncCredentials.jwt(accessToken)
SyncUser.logIn(with: creds, server: Constants.syncAuthURL, onCompletion: { [weak self](user, err) in
if let user = user {
self?.setDefaultRealmConfiguration(with: user)
let realm = try! Realm()
let identity = (user.identity)!
let person = Person()
person.id = identity
try! realm.write {
realm.add(person, update: true)
}
self?.performSegue(withIdentifier: "showProfile", sender: self)
}
})
此人已在云服务器上成功创建。
在下一个viewcontroller中,我想根据id来获取对象:
let realm = try! Realm()
guard let uuid = SyncUser.current?.identity! else { return }
let person = realm.objects(Person.self).filter("id = %@", uuid).first
try! realm.write {
person?.name = "test"
}
这个人总是零,我也尝试用主键查询对象,但是没有成功。
Person类如下:
class Person : Object {
@objc dynamic var id = ""
@objc dynamic var created: Date = Date()
@objc dynamic var name = ""
@objc dynamic var email = ""
@objc dynamic var avatar : Data?
override static func primaryKey() -> String? {
return "id"
}
}
更新
我创建了一个只有一个Viewcontroller和Person类的新应用:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let creds = SyncCredentials.usernamePassword(username: "admin", password: "test")
SyncUser.logIn(with: creds, server: Constants.AUTH_URL, onCompletion: { (user, err) in
if let user = user {
var config = user.configuration(realmURL: Constants.REALM_URL)
config.objectTypes = [Person.self]
Realm.asyncOpen(configuration: config, callback: { (realm, error) in
guard let realm = realm else {return}
let objects = realm.objects(Person.self)
print(objects) // always empty why???
try! realm.write {
let p = Person()
p.id = "test"
realm.add(p)
}
print(objects) // one object
})
}
})
}
}
与其他问题一样,此人已成功添加到云中。但是当我重新启动应用程序时,第一个查询中的对象为空。也许我想念对同步领域有所了解?
答案 0 :(得分:0)
let results = realm.objects(Person.self)
let subscription = results.subscribe()
print(results)
解决我的问题