【发布时间】:2016-09-10 09:45:44
【问题描述】:
我真的很想在我的 Swift 代码中使用更简单的经典 try catch 块,但我找不到任何可以做到这一点的东西。
我只需要:
try {
// some code that causes a crash.
}
catch {
// okay well that crashed, so lets ignore this block and move on.
}
这是我的困境,当 TableView 重新加载新数据时,一些信息仍位于 RAM 中,这会在 tableView 上调用 didEndDisplayingCell 并使用新的空数据源崩溃。
所以我经常抛出异常Index out of range
我试过了:
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
do {
let imageMessageBody = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody
let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
cell.willEndDisplayingCell()
} catch {
print("Swift try catch is confusing...")
}
}
我也试过这个:
func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
print(indexPath.section)
print(indexPath.row)
if msgSections.count != 0 {
if let msg = msgSections[indexPath.section].msg[indexPath.row] as? ImageMessageBody {
let cell = tableView.dequeueReusableCellWithIdentifier("ImageUploadCell", forIndexPath: indexPath) as! ImageCell
cell.willEndDisplayingCell()
}
}
}
这是一个非常低优先级的代码块,我已经浪费了很多时间来试错,以确定 swift 内置的哪个错误处理程序适用于似乎非常独特的情况,当我有大量的场景时,比如这是代码可能崩溃的地方,它不会对用户体验产生任何影响。
简而言之,我不需要任何花哨的东西,但 Swift 似乎有非常具体的错误处理程序,这些错误处理程序根据我是从函数返回值获取值还是从可能不存在的数组索引获取值而有所不同.
是否像其他所有流行的编程语言一样在 Swift 上进行简单的 try catch?
【问题讨论】:
-
您似乎正在尝试解决错误的问题。您应该解决在重新加载表视图后为什么在旧数据上调用
didEndDisplayCell的问题。这没有任何意义。为什么会这样?您是否在后台线程上更新表视图的数据?这是一个可能的问题。 -
一般从不自己调用包含
did、will和should的委托方法。它们由框架调用。 -
你必须在通过索引访问之前检查数组的计数来处理这个问题。
-
你有没有弄清楚为什么会发生这种情况?
标签: ios swift uitableview