我在网上找到的所有解决方案都是针对本地领域的,而不是同步领域(我使用的是基于查询的同步)。如何为同步域做好这件事呢?
我有一个Shop对象和一个Item对象。Shop有很多项。用户可以浏览项目,并应看到该项目属于哪个商店。非常简单和直接的场景。
在Shop类中,我有:
let items = List<Item>()在Item类中,我有
let shops = LinkingObjects(fromType: Shop.self, property: "items")
var shop: Shop? { return shops.first }领域查询如下所示:
private var realm : Realm!
private var subscriptionToken : NotificationToken?
private var syncSubscription : SyncSubscription!
...
...
...
let items = realm.objects(Item.self)
syncSubscriptionItem = items.subscribe()
subscriptionTokenItem = syncSubscriptionItem.observe(\.state, options: .initial) { state in
if state == .complete {
let shopName = items[0].shop?.name // Shop is always nil
}
}只有当店主登录到应用程序中时,我才能看到店铺,这意味着Realm已经将店铺信息同步到本地Realm。但对于其他设备上的用户,商店永远不会同步。但是如何通过这种反向链接为所有其他用户同步商店呢?
附上截图是为了阐明我的意思:

发布于 2020-05-09 22:58:24
我花了一分钟写了一些基于你的代码。问题中的代码不完整,所以我将所有其他元素添加到代码中,以绘制更完整的图景。这里没有真正的错误检查,所以请确保你添加了它。这是为我工作,并输出所有的项目相关的商店
var items: Results<Item>? = nil
var notificationToken: NotificationToken? = nil
var subscriptionToken: NotificationToken? = nil
var subscription: SyncSubscription<Item>!
var realm: Realm!
func setupItems() {
let config = SyncUser.current?.configuration()
self.realm = try! Realm(configuration: config!)
self.items = self.realm.objects(Item.self)
self.subscription = self.items!.subscribe(named: "my-items")
self.subscriptionToken = subscription.observe(\.state, options: .initial) { state in
if state == .complete {
print("subscription: queried data has been synced")
} else {
print("Subscription State: \(state)")
}
}
self.notificationToken = self.items!.observe { changes in
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
print("notification: initial results are populated")
for item in self.items! {
if let shop = item.shop {
print(shop.name)
} else {
print("\(item.itemName) has no shop")
}
}
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed
print("notification: results, inserted, deleteed or modified")
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}
}https://stackoverflow.com/questions/61662357
复制相似问题