首页 > 解决方案 > UITableView Swift 中的断言失败

问题描述

我在我相当大的 iOS 项目中遇到了这个错误(其中肯定有超过 15 个不同的表视图)。所以我的问题是,我怎么知道哪个 tableView 给了我这个错误?可能吗?Xcode 总是在 AppDelegate 中显示错误。

完整的错误描述:

2019-01-29 12:24:24.189428+0100 OrdersApp[28886:8731092] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKitCore/UIKit-3698.94.10/UITableView.m:2062
2019-01-29 12:24:24.190710+0100 OrdersApp[28886:8731092] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(0x234fa0ec4 0x234171a40 0x234eb6b3c 0x2359a51d0 0x2624762c8 0x26248e614 0x26248ea20 0x1023b6c84 0x102399fa0 0x103d9b824 0x103d9cdc8 0x103daaa78 0x234f30df4 0x234f2bcbc 0x234f2b1f0 0x2371a4584 0x262282d40 0x10246a4b0 0x2349eabb4)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

标签: iosswiftuitableview

解决方案


正如它在这里解释的那样:

2019-01-29 12:24:24.190710+0100 OrdersApp[28886:8731092] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 1.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

您可能从数据源中删除了一些数据,并UITableViewCell在结束 tableView 更新之前忘记删除相应的数据。

您应该按顺序执行以下操作:

tableView.beginUpdates()
dataSource.remove(at: <#index#>)
tableView.deleteRows(at: [<#indexPath#>], with: .automatic)
tableView.endUpdates()

所有抛出的异常UIKit都可以用异常断点捕获。它将指向崩溃前的点,您可以检测到它。

异常断点

并且不要忘记尝试模拟器。捕获这些异常会很棒。


推荐阅读