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

时间:2019-05-07 04:50:22

标签: 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())";
    }

1 个答案:

答案 0 :(得分:-1)

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

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

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