具有多个数组的 PFQuery 到 UITableView

PFQuery with multiple arrays into UITableView

这是我用来查询数据库的函数:

func loadRestaurantMeals(){
        let mealsQuery = PFQuery(className: "Meals")
        mealsQuery.whereKey("Restaurant", equalTo: selectedRestaurant!)
        mealsQuery.whereKey("MealCategory", equalTo: selectedMenuHeading!)
        mealsQuery.findObjectsInBackgroundWithBlock{ (objects: [PFObject]?, error: NSError?) -> Void in
            if error == nil{
                //after successfull fetch
                if let fetchedMeals = objects{
                    print("c")

                    for fetchedMeal in fetchedMeals{
                        print("writing to name")
                        self.restaurantMealsArray.append(fetchedMeal.objectForKey("MealName") as! String)
                        print("writing to description")
                        self.mealsDescriptionArray.append(fetchedMeal.objectForKey("MealDescription") as! String)
                        print("writing to price")
                        self.mealsPriceArray.append(fetchedMeal.objectForKey("MealPrice") as! Double)
                    }

                    //display content
                    print("before reload data")
                    self.mealsTableView.reloadData()
                    print("reload data")
                }
            }else{
                // Log details of the failure
                print("Error: \(error!) \(error!.userInfo)")
            }
        }
    }

以下是所有 UITableView 函数:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return restaurantMealsArray.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("mealCell", forIndexPath: indexPath) as UITableViewCell
        print("a")
        cell.textLabel?.text = restaurantMealsArray[indexPath.row]
        print("b")
        cell.detailTextLabel?.text = mealsDescriptionArray[indexPath.row]
        print("c")
        //cell.label
        return cell
    }

出于某种原因,reloadData() 从未被调用。 控制台报告以下错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

这可能是什么原因?

我想问题是由以下行引起的:

self.mealsPriceArray.append(fetchedMeal.objectForKey("MealPrice") as! Double)

objectForKey returns 一个对象,但您强制转换为 Double,但这是行不通的。试试这个:

self.mealsPriceArray.append((fetchedMeal.objectForKey("MealPrice") as! NSNumber).doubleValue) 

(假设您的 mealsPriceArray[Double]

更好的是: 因为您永远无法确定从任何外部来源获得的数据,所以您应该真正使用 ? 而不是 ! mealPrice 和其他数据字段:

if let mealPrice = fetchedMeal.objectForKey("MealPrice") as? NSNumber {
    self.mealsPriceArray.append(mealPrice.doubleValue)
}