Xcode Coredata:从一个 CoreData 实体获取两个值并插入到循环函数内的另一个 CoreData 实体

Xcode Coredata: Fetch two values from one CoreData entity and insert to another CoreData entity within loop function

我是 CoreData 的新手 fetching/display,到目前为止能够从 JSON 提取中保存到 CoreData。

获取的数据是机场信息数组,只有三项; airport_code、access_point 和 image_url。

我需要为每个获取的项目再添加两个值 - 一个纬度和经度坐标,它存储在另一个具有匹配 airport_code item/attribute.

的 CoreData 实体中

任何人都可以提供一些指导,说明如何使用 airport_code 的谓词值创建一个单独的函数来在循环序列中查询其他 CoreData 吗?我附上了到目前为止的代码:

    func saveData(context: NSManagedObjectContext){


        xArray.forEach { (data) in
            
            let entity = Airports(context: context)
            entity.airport_code = data.airport_code
            entity.access_points = data.access_points
            entity.image_url = data.image_url
            entity.lat = getLat()
            entity.lon = getLon()
        }
        
        do{
            try context.save()
            print("Success Saving to CoreData: \(xArray.count)")
        }
        catch{
            print("Error Saving to CoreData \(error.localizedDescription)")
        }
    }
    
    
    func getLat() -> String {
        @FetchRequest(entity: AllAirports.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \AllAirports.airport_code, ascending: true)])
        var results: FetchedResults<AllAirports>
        //this is where Im lost as to how to query this CoreData to fetch the LON value when there is a match to the data.airport_code in the loop above.
        
        return latResults
    }

    func getLon() -> String {
        @FetchRequest(entity: AllAirports.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \AllAirports.airport_code, ascending: true)])
        var results: FetchedResults<AllAirports>
        //this is where Im lost as to how to query this CoreData to fetch the LON value when there is a match to the data.airport_code in the loop above.
        
        return lonResults
    }



func fetchData(context: NSManagedObjectContext) {
// this function performs a JSON parse and returns the xArray above
….

首先,您想查看此处的响应 以了解程序化提取请求的外观。

据我了解您现在的问题,您想编写两个方法 getLat()getLon() 来获取机场的坐标。

我建议编写如下所示的单个函数,它使用给定代码和 returns 找到坐标的元组在 AllAirports 中查找您的机场。

func getCoord(airport_code: String) -> (lon: Double, lat: Double)? {
    let request: NSFetchRequest<AllAirports> = AllAirports.fetchRequest()
    request.predicate = NSPredicate(format: "airport_code == %@", airport_code)

    if let result = try? viewContext.fetch(request) {
        print("Found \(result.count) airports matching \(airport_code)")

        // Just return the first matched airport
        if let first = result.first {
            return (first.longitude, first.latitude)
        }
    }

    return nil
}

更好的解决方案是为您添加一个扩展 AllAirports 其中 returns 一个给定条目(希望是唯一的!) airport_code:

extension AllAirports {
    static func airport(byCode airportCode: String, in context: NSManagedObjectContext) -> AllAirports? {
        let request: NSFetchRequest<AllAirports> = fetchRequest()
        request.predicate = NSPredicate(format: "airport_code == %@", airportCode)

        if let result = try? context.fetch(request) {
            return result.first
        }
        return nil
    }
}

这可以在您的代码中使用,如下所示:

    func saveData(context: NSManagedObjectContext){
        xArray.forEach { (data) in
            
            let entity = Airports(context: context)
            entity.airport_code = data.airport_code
            entity.access_points = data.access_points
            entity.image_url = data.image_url
            if let airport = AllAirports.airport(byCode: data.airport_code, in: context) {
                entity.lat = airport.latitude
                entity.lon = airport.longitude
            }
        }