如何在 @FetchRequest 中检索最后创建的 Core Data 父实体及其 1 到多个相关实体?

问题描述 投票:0回答:1

在核心数据中有 2 个实体 - LocationSetLocation 处于一对多关系 我想获取与上次创建的 LocationSet 相关的所有 Location 子项(使用其 .created date 属性)以在 View 中使用

我的 2 个 FetchRequest 可以单独工作,但我想使用第一次 Fetch 中返回的 LocationSet 作为第二次获取 Location 子项

的谓词

这些是我对每个实体的 FetchRequest,

@FetchRequest(entity: LocationSet.entity()
 ,sortDescriptors: [NSSortDescriptor(keyPath: \LocationSet.created, ascending: true)]
 )var fetchedLocSets: FetchedResults<LocationSet>

@FetchRequest(entity: Location.entity()
 ,sortDescriptors: [NSSortDescriptor(keyPath: \Location.name, ascending: true)]
 )var fetchedLocations: FetchedResults<Location>

我尝试在 init() 中执行此操作,但它不起作用并且似乎过于复杂,因此认为这必须有一个更优雅的解决方案?

我尝试使用 init() 首先执行 LocationSet 获取,然后在 Location 获取中使用,但没有成功,并且还出现紫色错误

Accessing StateObject's object without being installed on a View. This will create a new instance each time.

init(){
  let requestSets: NSFetchRequest<LocationSet> = LocationSet.fetchRequest()
  requestSets.sortDescriptors = [NSSortDescriptor(keyPath: \LocationSet.name, ascending: true)]
  let fetchLS = FetchRequest<LocationSet>(fetchRequest: requestSets)
       
  if let locset = fetchLS.wrappedValue.first {
    let request: NSFetchRequest<Location> = Location.fetchRequest()
    request.sortDescriptors = [NSSortDescriptor(keyPath: \Location.name, ascending: true)]
    request.predicate = NSPredicate(format: "set_ofLocations == %@", locset)
    _fetchedLocations = FetchRequest<Location>(fetchRequest: request)
  }
}
swiftui core-location nsfetchrequest fetchrequest
1个回答
0
投票

我几乎放弃了

@FetchRequest
中的
View
,因为与整个 CoreData 相比,它的功能非常有限。

我通常做的是:

  • 创建一个管理器对象来访问我的
    CoreData
    模型(我的数据管理器是
    @globalActor
    ,可以更轻松地促进后台获取,但这不是必需的,并且如果您不能 100% 适应合并来自不同的线程。)
  • onAppear
    中,我使用管理器在
    Task
    中获取数据,一旦检索,我就会使用获取的数据更新视图上的
    @State
    属性(使用
    MainActor.run
    以避免从后台上下文获取时出现更多紫色错误) )
© www.soinside.com 2019 - 2024. All rights reserved.