swift - 基于查询的同步领域 LinkingObjects 返回 nil
问题描述
我在网上找到的所有解决方案都是针对本地领域,而不是同步领域(我使用的是基于查询的同步)。如何为同步的领域做正确的事情?
我有一个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。但对于其他设备上的用户,商店永远不会同步。但是如何通过这种类型的反向链接为所有其他用户同步商店?
附上屏幕截图以澄清我的意思:
解决方案
我花了一分钟,根据您的代码编写了一些代码。问题中的代码不完整,因此我将所有其他元素添加到代码中以绘制更完整的图片。这里真的没有错误检查,所以一定要添加它。这对我有用,并输出所有与商店相关的物品
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)")
}
}
}
推荐阅读
- javascript - 存储在本地存储中的 Firebase 用户不起作用?(javascript)
- javascript - 尝试使用此关键字将函数变量附加到文档
- java - JSP:加入 2 个实体时出现 NumberFormatException
- ssas - SSAS 表格模型:计算表和 DAX 之间的差异
- mysql - MySQL“自动”加密每个会话
- r - 在 R Data.Table 中创建一个计数器列,在另一列上有一个条件
- c - 将“>>”作为 execv 参数传递?
- webpack - 停止 webpack-dev-server 聚焦已打开站点的浏览器选项卡
- node.js - 如何在 electron-forge 中配置 electronWinstallerConfig 以指定设置的自定义安装路径?
- c# - 为什么 List.Add 方法不起作用?