UITableView 未显示正确的行数

UITableView not displaying the correct number of rows

我的 cellForRow at index path 函数有问题,遗憾的是我无法发现它。所以我求助于这个机构的好心人。 我执行一个获取请求 returns Floors 类型的结果数组(这是我的实体)。我在table中只有一节,结果只有一行。如果我声明 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)")

    }
}

正如 Fahim 所说,您需要为用于显示 table:

的提取设置排序描述符
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()