簡體   English   中英

點擊按鈕將新行添加到UITableView后,iOS應用程序崩潰

[英]iOS app crashes upon tapping button to add new Row to a 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM