gpt4 book ai didi

swift - NSPredicate 一对多关系查询示例

转载 作者:行者123 更新时间:2023-11-28 14:19:08 25 4
gpt4 key购买 nike

This is my core data model

关系如下: enter image description here

关系是一条通往许多地点的路线。第一个问题是 Location 中是否应该有名称属性(routeName)?例如,在 DB2 中,您总是命名主键,但我在 Core Data 中看到的大多数示例都在关系定义中处理主键。

以下是 DB Browser for sqlite 的表格摘录。

Table Excerpts

代码如下:

    final class CoreDataManager {

static let sharedInstances = CoreDataManager()

let managedContext: NSManagedObjectContext

private init(){
let application = UIApplication.shared.delegate as! AppDelegate
managedContext = application.persistentContainer.viewContext
}


func createRoute(name: String) -> Route {
let routeEntity = NSEntityDescription.entity(forEntityName: "Route", in: managedContext)!
let route = NSManagedObject(entity: routeEntity, insertInto: managedContext)

route.setValue(name, forKeyPath: "name")

route.setValue(Date().timeIntervalSince1970, forKey: "ts")

do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}

return route as! Route
}

func createLocation(loc: CLLocation, route: Route) {

let locationEntity = NSEntityDescription.entity(forEntityName: "Location", in: managedContext)!
let location = NSManagedObject(entity: locationEntity, insertInto: managedContext)

location.setValue(loc.coordinate.latitude, forKeyPath: "latitude")
location.setValue(loc.coordinate.longitude, forKeyPath: "longitude")
location.setValue(loc.altitude, forKeyPath: "altitude")
location.setValue(loc.timestamp, forKeyPath: "ts")
location.setValue(route, forKeyPath: "route")

do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}

func getAllRoutes () -> [Route] {
let routeFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Route")
let routeResults = try! managedContext.fetch(routeFetch)
return routeResults as! [Route]
}

func getLocationsByRoute (name: String) -> [Location] {
let locFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Location")

//select * from ZLOCATION, ZROUTE where ZLOCATION.ZROUTE = ZROUTE.Z_PK and ZROUTE.ZNAME = ?
locFetch.predicate = NSPredicate(format: "locations.route = %@", name)
locFetch.sortDescriptors = [NSSortDescriptor.init(key: "ts", ascending: false)]

let locations = try! managedContext.fetch(locFetch)

return locations as! [Location]
}

如果位置表中没有主键,我该如何创建查询以获取给定路线的所有位置?您可以在代码中看到我有一个 getLocationsByRoute 方法,但无法使查询正常工作。任何帮助将不胜感激。

最佳答案

  • 如果您有 Route对象,从 locations 中获取位置属性(property)
  • 如果您必须获取对象,请使用谓词格式

    locFetch.predicate = NSPredicate(format: "route.name = %@", name)

    关键路径总是<relationship name>.<attribute name> – 在本例中获取所有 Location name 的对象的相关route等于给定的名字。

关于swift - NSPredicate 一对多关系查询示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52010925/

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