gpt4 book ai didi

ios - CoreStore如何观察数据库的变化

转载 作者:行者123 更新时间:2023-11-29 05:32:17 24 4
gpt4 key购买 nike

我需要在导入发生后观察Entity的变化。

目前我有下一个逻辑:

  1. 将带有临时标识符 (NSManagedObject.objectId) 的 Entity 保存到本地核心数据存储。
  2. 通过 Alamofire POST 请求将 Entity 发送到服务器。
  3. 服务器生成 JSON 并使用几乎相同的实体详细信息进行回复,但使用修改后的标识符(之前为 NSManagedObject.objectId)。因此本地实体 id 将使用服务器 id 进行更新。
  4. 现在,当我收到新的 JSON 时,我会执行 transaction.importUniqueObjects

在此步骤中,我想通知我的数据源有关更改的信息。并使用更新的标识符重新获取数据。

所以我的DataSource在数组中有一些Entities,当我使用这个数据源来显示数据时,它仍然是我之前获取的数组中的静态信息,但是作为您可以在第 4 步中看到,我已经通过 CoreStore 导入更新了核心数据存储,并且希望 DataSource 的数组也更新。

我在CoreStore中找到了一些关于ListMonitor的信息并尝试使用它。正如我所看到的,这个方法在更新时有效

func listMonitorDidChange(_ Monitor: ListMonitor)

但我尝试以某种方式重新获取数据。看起来监视器已经包含一些最新信息。

但是当我这样做时:

func listMonitorDidChange(_ monitor: ListMonitor<MyEntity>) {

let entities = try? CoreStore.fetchAll(
From<MyEntity>()
.orderBy(.ascending(\.name))
) // THERE IS STILL old information in database, but monitor instance shows new info.
}

然后代码就变成了这样:

func listMonitorDidChange(_ monitor: ListMonitor<MyEntity>) {

var myEntitiesFromMonitor = [MyEntity]()

for index in 0...monitor.numberOfObjects() {
myEntitiesFromMonitor.append(monitor[index])
}

if myEntitiesFromMonitor.count > 0 {
// HERE we update DataSource
updateData(with: myEntitiesFromMonitor)
}

}

不确定我是否走对了路。

最佳答案

如有错误,请指正:

据我了解,每次核心数据因新更改而更新时,监视器也会更新。我还没有深入研究它是如何通过一些 CoreData 上下文通知或其他方式实现的,但是当您通过 CoreStore 事务执行某些操作(例如创建、更新或删除对象或任何您想要的操作)后,监视器就会更新。它还具有您需要在您想要观察数据模型的任何更改的类中实现的回调函数:

您的类,例如数据源或某些服务,甚至某些 View Controller (如果您不使用任何 MVVP 或 VIPER 或其他设计模式)需要符合 ListObserver 协议(protocol),以防您想要不要只听一个物体。

这些功能如下:

    func listMonitorDidChange(monitor: ListMonitor<MyPersonEntity>) {
// Here I reload my tableview and this monitor already has all needed info about sections and rows depend how you setup monitor.
// So you classVariableMonitor which I provide below already has up to date state after any changes with data.
}



func listMonitorDidRefetch(monitor: ListMonitor<MyPersonEntity>) {
// Not sure for which purposes it. I have not received this call yet
}



typealias ListEntityType = ExerciseEntity

let classVariableMonitor = CoreStore.monitorSectionedList(
From<ListEntityType>()
.sectionBy(#keyPath(ListEntityType.muscle.name)) { (sectionName) -> String? in
"\(String(describing: sectionName)) years old"
}
.orderBy(.ascending(\.name))
.where(
format: "%K == %@",
#keyPath(ListEntityType.name),
"Search string")
)

记录的所有其他内容 here这样您就可以找到如何在 tableview 数据源函数中从监视器中提取信息的信息。

感谢@MartinM 的建议!

关于ios - CoreStore如何观察数据库的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com