我对Couchbase和Nosql都很陌生。我可以上传CouchBase DB上的数据,并通过枚举器检索这些数据,并在表视图中显示它们。但是我想通过观察者检索数据,它可以观察到DB上的变化,并且我可以从Couchbase DB中立即将这些数据保存在本地DB中。我正在使用Swift4 Xcode9.1。有人能帮我吗?
发布于 2017-12-31 05:31:33
通过以下方法,可以在Swift4中观察到数据库的变化
NotificationCenter.default.addObserver(forName: NSNotification.Name.cblDatabaseChange, object: database, queue: nil) {
(notification) -> Void in
if let changes = notification.userInfo!["changes"] as? [CBLDatabaseChange] {
for change in changes {
NSLog("Document '%@' changed.", change.documentID)
let document = self.database.document(withID: change.documentID)
var properties = document?.properties
if let id = properties?["id"] as? String, let name = properties?["name"] as? String, let age = properties?["age"] as? String {
self.person.uniqueIDs = Int(id)
print(self.person.uniqueIDs ?? "i")
self.person.names = name
print(self.person.names ?? "n")
self.person.ages = Int(age)
print(self.person.ages ?? "a")
self.core.savedObjects(id: Int(self.person.uniqueIDs), name: String(self.person.names), age: Int(self.person.ages))
}
}
}
}发布于 2017-12-27 09:21:51
在获取数据时尝试使用下面的方法,这样它将检测到DB中的变化。
使一个功能如下所示:
fileprivate func addLiveQueryObserverAndStartObserving() {
guard let liveQuery = liveQuery else {
return
}
// 1. iOS Specific. Add observer to the live Query object
liveQuery.addObserver(self, forKeyPath: "rows", options: NSKeyValueObservingOptions.new, context: nil)
// 2. Start observing changes
liveQuery.start()
}还请参考此动脉套件
https://stackoverflow.com/questions/47989254
复制相似问题