【发布时间】:2019-03-29 21:54:26
【问题描述】:
我有一个 UI Table VIew,其中包含从 URL 异步加载的数据。对于
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.notificationsResponse?.data?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let notification = notificationsResponse?.data![indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! NotificationsViewCell
cell.setNotification(notification: notification!)
return cell
}
var notificationsResponse:NotificationsResponse?
我收到类似
的错误线程 1:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)
在这一行
return (self.notificationsResponse?.data?.count)!
我不知道这有什么问题。我正面临这个问题,可能是由于对 swift 理解不佳
谁能帮帮我?
【问题讨论】:
-
避免强制展开(使用
!)。据我猜测,它是异步的,所以响应还没有出现,所以你会崩溃。改用return self.notificationsResponse?.data?.count ?? 0之类的方法。 -
可选链接失败 + 强制解包 = 崩溃。
-
谢谢@Larme 这很好用。
-
避免强制展开 (
!)。如果您不是 100% 存在价值,这将使您的应用程序崩溃。当涉及到异步调用时,请确保更新主线程上的值。 -
除了这个问题,强烈建议您不要使用 通知响应 作为数据源数组。