UITableView无法显示正确的行数

时间:2017-03-26 17:04:27

标签: swift uitableview core-data swift3 nsfetchrequest

我的索引路径功能中的cellForRow有问题,我无法遗憾地发现它。所以我转向这个机构的善良人士。 我执行一个获取请求,返回类型为Floors的结果数组(这是我的实体)。我在表中只有一个部分,结果只有一行。如果我声明5层,我只得到一行文本值为" 4"。它总是我声明的价值 - 1.有人可以看看我的代码并帮我发现问题吗?谢谢你,亲切的问候。

class AssignNumberOfRoomsForFloorsVC: UITableViewController {

//MARK: - Properties

private var managedObjectContext: NSManagedObjectContext!

private var storedFloors = [Floors]()


//MARK: - Actions

override func viewDidLoad() {
    super.viewDidLoad()
    managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    loadFloorData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

private func loadFloorData() {
    let request: NSFetchRequest<Floors> = Floors.fetchRequest()
    request.returnsObjectsAsFaults = false
    do {
        storedFloors = try managedObjectContext.fetch(request)
        self.tableView.reloadData()
    }
    catch {
        print("could not load data from core \(error.localizedDescription)")

    }
}

// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "floor cell", for: indexPath) as! FloorCell
    let floorItem = storedFloors[indexPath.row]
    cell.floorNumberTxt.text = String(floorItem.floorNumber)
    return cell
}

此代码用于设置楼层数:

 @IBAction private func setTheNumberOfFloors(_ sender: UIButton) {
    let house = NSEntityDescription.insertNewObject(forEntityName: "House", into: managedObjectContext) as! House
    house.numberOfFloors = floorNumberValue
    print(" the number of floors in the house is: \(house)")

    loadFloorData()
    for floor in storedFloors {
        for i in 0...floor.numberOfFloors - 1 {
            let instance = NSEntityDescription.insertNewObject(forEntityName: "Floors", into: managedObjectContext) as! Floors
            instance.floorNumber = i
            print("\(instance)")
            house.addToFloors(instance)
        }
    }
 private func loadFloorData() {
    let request = NSFetchRequest<House>(entityName: "House")
    request.returnsObjectsAsFaults = false
    do {
        storedFloors = try managedObjectContext.fetch(request)
    }
    catch {
        print("could not load data from core \(error.localizedDescription)")

    }
}

1 个答案:

答案 0 :(得分:1)

正如Fahim所说,你需要为用于显示表的fetch设置一个排序描述符:

request.sortDescriptors = [NSSortDescriptor(key: #keyPath(Floors.floorNumber), ascending: true)]

此外,请确保在插入新实体或进行任何修改后保存moc:

        do {
            try managedObjectContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }

或者,如果您使用的是标准生成代码:

UIApplication.shared.delegate.saveContext()