从一对多关系中的核心数据中获取结果

时间:2017-05-16 00:26:46

标签: ios swift uitableview core-data

我看到的所有相关问题都在Objective C中,但我使用的是Swift。 我在核心数据中有一对多关系,一个“当前”实体与许多“预测”实体有关系。我设法保存并获取“当前”实体,但未能为我的表“预测”实体的“匹配”执行此操作。 Forecast实体也应该显示在UITableView中。 这就是我现在所拥有的。我正在尝试创建的数组始终为空。我需要一些帮助:

guard let stack = (UIApplication.shared.delegate as! AppDelegate).stack else {return}
        let sortDescriptors = [NSSortDescriptor(key: "city_id_forecast", ascending: true)]
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Forecast")
        fetchRequest.sortDescriptors = sortDescriptors
        fetchRequest.predicate = NSPredicate(format: "main==%@", currentFetched!)
        if (currentFetched==nil){
            print("current fetched is nil")
        }
        else{
            print("currentFetched is not nil")
        }
        let fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: stack.context, sectionNameKeyPath: "city_id_forecast", cacheName: nil)
        do {try fetchedResultController.performFetch()}
        catch {print ("error in performing fetch results\(error)")}
        let fetched = fetchedResultController.fetchedObjects
        //let fetched = fetchedResultController.
        let count = fetched?.count
        print ("count of fetched forecast!: \(count!)")
        for i in 0..<count!{
            let currentFetched = fetched?[i] as? Forecast
            let dateForecast = currentFetched?.value(forKeyPath: "date_forecast") as! String
            let tempForecast = currentFetched?.value(forKeyPath: "temperature_forecast") as! String
            let iconForecast = currentFetched?.value(forKeyPath: "icon_forecast") as! String
            let forecastElement = "\(dateForecast), \(tempForecast), \(iconForecast)"

            forecastArray.append(forecastElement)

0 个答案:

没有答案