0

当用户登录时,我创建了一个 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)
     }                    
})

在云服务器上成功创建人员。

在下一个视图控制器中,我喜欢根据 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
            })
        }
    })
  }
}

与我的其他问题一样,该人已成功添加到云中。但是当我重新启动应用程序时,第一个查询中的对象是空的。也许我想念对同步领域的理解?

4

1 回答 1

0
let results = realm.objects(Person.self)
let subscription = results.subscribe()
print(results)

解决我的问题

于 2018-11-29T22:01:15.843 回答