iOS 应用程序在点击按钮将新行添加到 UITableView 时崩溃

标签 ios swift uitableview

我正在使用 Swift 创建一个 iOS 应用程序,以帮助我使用 UITableView 跟踪学校的作业。但是,在点击添加按钮时,当它尝试添加新行时,应用程序崩溃了。我看过无数 Brian Voong、Sean Allen、Kilo Loco 等人的教程,并阅读了 Apple 的教程和文档,但仍然无法弄清楚哪里出了问题。我错过了什么?我编码不当吗?

崩溃后,我收到错误消息:

2019-05-06 23:28:58.200728-0500 AssignmentTracker[18768:1102271] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/joshroot/Library/Developer/CoreSimulator/Devices/45F175C3-2A67-4EB6-9F1D-DE8503AEEDA8/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2019-05-06 23:28:58.201136-0500 AssignmentTracker[18768:1102271] [MC] Reading from private effective user settings.
2019-05-06 23:29:18.701240-0500 AssignmentTracker[18768:1102271] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore_Sim/UIKit-3698.103.12/UITableView.m:1821
2019-05-06 23:29:18.713115-0500 AssignmentTracker[18768:1102271] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001116416fb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000010f98dac5 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000111641482 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x000000010f3db927 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 194
    4   UIKitCore                           0x000000011aad86a7 -[UITableView _endCellAnimationsWithContext:] + 8315
    5   UIKitCore                           0x000000011aaf3e6f -[UITableView endUpdates] + 74
    6   AssignmentTracker                   0x000000010f0900e1 $s17AssignmentTracker14ViewControllerC9insertRow10assignmentyAA0A0C_tF + 1169
    7   AssignmentTracker                   0x000000010f08fb6b $s17AssignmentTracker14ViewControllerC15addButtonTappedyyF + 6107
    8   AssignmentTracker                   0x000000010f08fc34 $s17AssignmentTracker14ViewControllerC15addButtonTappedyyFTo + 36
    9   UIKitCore                           0x000000011a8de204 -[UIApplication sendAction:to:from:forEvent:] + 83
    10  UIKitCore                           0x000000011a333c19 -[UIControl sendAction:to:forEvent:] + 67
    11  UIKitCore                           0x000000011a333f36 -[UIControl _sendActionsForEvents:withEvent:] + 450
    12  UIKitCore                           0x000000011a332eec -[UIControl touchesEnded:withEvent:] + 583
    13  UIKitCore                           0x000000011a916eee -[UIWindow _sendTouchesForEvent:] + 2547
    14  UIKitCore                           0x000000011a9185d2 -[UIWindow sendEvent:] + 4079
    15  UIKitCore                           0x000000011a8f6d16 -[UIApplication sendEvent:] + 356
    16  UIKitCore                           0x000000011a9c7293 __dispatchPreprocessedEventFromEventQueue + 3232
    17  UIKitCore                           0x000000011a9c9bb9 __handleEventQueueInternal + 5911
    18  CoreFoundation                      0x00000001115a8be1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    19  CoreFoundation                      0x00000001115a8463 __CFRunLoopDoSources0 + 243
    20  CoreFoundation                      0x00000001115a2b1f __CFRunLoopRun + 1231
    21  CoreFoundation                      0x00000001115a2302 CFRunLoopRunSpecific + 626
    22  GraphicsServices                    0x0000000115ad82fe GSEventRunModal + 65
    23  UIKitCore                           0x000000011a8dcba2 UIApplicationMain + 140
    24  AssignmentTracker                   0x000000010f0920ab main + 75
    25  libdyld.dylib                       0x0000000112a49541 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

代码在 - ViewController.swift:

import UIKit;

class ViewController: UIViewController {

    var assignments: [Assignment] = [Assignment]();

    @IBOutlet weak var assignmentsTable: UITableView!;
    @IBOutlet weak var doneButton: DoneButton!;
    @IBOutlet weak var assignmentNameField: UITextField!;
    @IBOutlet weak var assignmentDateAssignedField: UITextField!;
    @IBOutlet weak var assignmentDueDateField: UITextField!;
    @IBOutlet weak var assignmentWeightOfAssignmentField: UITextField!;

    var textFields: [UITextField] = [];

    override func viewDidLoad() {
        super.viewDidLoad();

        textFields =
        [
            assignmentNameField,
            assignmentDateAssignedField,
            assignmentDueDateField,
            assignmentWeightOfAssignmentField
        ];

        doneButton.addTarget(self, action: #selector(addButtonTapped), for: .touchUpInside);

        Util.setupViewControllerSytles(fields: textFields, viewController: self);
    }

    @objc func addButtonTapped() {
        doneButton.shake();

        let isDataValid: Bool = ValidationUtil.isValidData(viewController: self, name: assignmentNameField.text!, dueDate: assignmentDueDateField.text!, dateAssigned: assignmentDateAssignedField.text!, assignmentWeight: assignmentWeightOfAssignmentField.text!);

        if (isDataValid) {
            insertRow(assignment: Assignment(name: assignmentNameField.text!, dueDate: assignmentDueDateField.text!, assignedDate: assignmentDateAssignedField.text!, assignmentWeight: Double(assignmentWeightOfAssignmentField.text!)!));
        }
    }

    func insertRow(assignment: Assignment) {
        assignments.append(assignment);

        let indexPath: IndexPath = IndexPath(row: assignments.count - 1, section: 0);

        assignmentsTable.beginUpdates();
        assignmentsTable.insertRows(at: [indexPath], with: .bottom);
        assignmentsTable.endUpdates();

        Util.cleanUp(fields: textFields);
    }
}

extension ViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true);

        return false;
    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return assignments.count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let assignment = assignments[indexPath.row];

        let cell = tableView.dequeueReusableCell(withIdentifier: "AssignmentCell") as! AssignmentCell;
        Util.setupAssignmentCell(cell: cell, assignment: assignment);

        return cell;
    }
}

setupAssignmentCell 函数

static func setupAssignmentCell(cell: AssignmentCell, assignment: Assignment) {
        cell.assignmentNameLabel.text = "Name: \(assignment.getName())";
        cell.assignmentDueDateLabel.text = "Due Date: \(assignment.getDueDate())";
        cell.assignmentAssignedDateLabel.text = "Assigned: \(assignment.getAssignedDate())";
        cell.assignmentWeightLabel.text = "Weight (%): \(assignment.getAssignmentWeight())";
    }

最佳答案

看起来问题是由于在调用 beginUpdates 函数之前更新了 assignments 数组引起的。

所以我建议的解决方案是在调用 beginUpdates 之后更改 assignments 数组,如下所示:

assignmentsTable.beginUpdates();
assignments.append(assignment);
let indexPath: IndexPath = IndexPath(row: assignments.count - 1, section: 0);
assignmentsTable.insertRows(at: [indexPath], with: .bottom);
assignmentsTable.endUpdates();

关于iOS 应用程序在点击按钮将新行添加到 UITableView 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015729/

相关文章:

ios - Facebook iOS invitable_friends返回空数据

ios - 快速设置模型类属性的值

ios - 点击后退按钮时如何在 UITableView 中保留更新的数据

swift - 火力地堡 swift : Converting Snapshots to Dictionary

ios - Flutter 设备抖动 iOS 插件

objective-c - Objective-c 中的属性问题

objective-c - UITableView 字幕没有出现

iphone - iOS 应用程序启动时崩溃

ios - Objective-C:获取每个表行的文本字段值

ios - 数据结构布局——NSMutableDictionary