我正在swift 4中创建一个领域对象,并尝试根据最新文档观察它的变化。
领域对象:
import Foundation
import RealmSwift
class Thing: Object{
@objc dynamic var id = UUID().uuidString
@objc dynamic var descriptionText: String = "xyxyx"
override static func primaryKey() -> String? {
return "id"
}
远程领域
extension Realm {
static func sharedDataRealm(callback: @escaping (Realm?, Swift.Error?) -> Void) {
SyncUser.logIn(with: Constants.syncCredentials, server: Constants.remoteAuthServer) { (remoteUser, error) in
if let user = remoteUser {
let sharedConfig = user.configuration(realmURL: Constants.remoteSharedRealmServer, fullSynchronization: true)
Realm.asyncOpen(configuration: sharedConfig, callback: callback)
} else {
callback(nil, error)
}
}
}
}
数据库层
class Database {
static let shared: Database = Database()
private init(){}
func saveThing(thing: Thing){
Realm.sharedDataRealm(callback: { (remoteRealm, error) in
if let realm = remoteRealm {
do { try realm.write { realm.add(thing, update: true)}
} catch {
print("error \(error)")
return
}
}
})
}
func updateText(onThing: Thing){
Realm.sharedDataRealm(callback: { (remoteRealm, error) in
if let realm = remoteRealm {
do { try realm.write { onThing.descriptionText = "\(arc4random())"}
} catch {
print("*** error \(error)")
return
}
}
})
}
}
问题观察者代码:
let thing = Thing()
Database.shared.saveThing(thing: thing)
_ = thing.observe { (change) in
switch change {
case .change(let properties):
for property in properties {
print("property \(property.name) has new value \(property.newValue as! String)")
}
case .error(let error):
print(" an error occured: \(error)")
case . deleted:
print(" thing was deleted")
}
}
其他观察者代码(添加了延迟。)
override func viewDidLoad() {
super.viewDidLoad()
var thing = Thing()
print ("*** created \(thing.descriptionText)")
Database.shared.saveThing(thing: thing)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(5000)) {
_ = thing.observe { (change) in
switch change {
case .change(let properties):
for property in properties {
print("*** property \(property.name) has new value \(property.newValue as! String)")
}
case .error(let error):
print("*** an error occured: \(error)")
case . deleted:
print("*** situation was deleted")
}
}
}
Database.shared.updateText(onThing: thing)
}
“问题观察者代码”崩溃,原因是“ thing.observe(..)”行上的“原因:'仅由Realm支持的对象支持更改通知'”。 “其他观察者代码”不会崩溃,因为我引入了从将对象添加到Realm的那一刻到开始观察它的那一刻之间的延迟。但是,对“事物”对象的更改仍然不会触发任何通知,并且不会运行新属性的打印。
根据我在编码方面的经验,我不必首先对延迟进行硬编码,以使领域首先真正完成对象的创建(和管理操作)。我认为此延迟是必需的,因为我居住在远离Realm区域的区域,并且可能存在一些延迟(?)。
1.在创建对象之后,有没有更好的方式开始观察对象而没有硬编码延迟?
2.为什么即使在附加观察者之后,执行updateText()函数时也没有通知?。
谢谢