我的应用程序中有一个表格 View ,当我启动我的应用程序时,它会在执行以下函数时崩溃。
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
// Configure the cell...
let cellId: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell
}
它在 var cell
行崩溃
它给出了以下错误:
我不知道我的代码有什么问题。
整个函数:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
// Configure the cell...
let cellId: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell
let data: NSManagedObject = mylist[ip.row] as NSManagedObject
cell.textLabel.text = data.valueForKeyPath("voornaam") as String
cell.detailTextLabel.text = data.valueForKeyPath("achternaam") as String
return cell
}
编辑: 我现在得到的是:(仍然给出同样的错误)
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
// Configure the cell...
let cellId: NSString = "Cell"
var cell: UITableViewCell? = tableView?.dequeueReusableCellWithIdentifier(cellId) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellId)
}
let data: NSManagedObject = mylist[indexPath.row] as NSManagedObject
cell!.textLabel.text = data.valueForKey("voornaam") as String
cell!.detailTextLabel.text = data.valueForKey("achternaam") as String
//cell!.textLabel.text = "Hoi"
return cell
}
最佳答案
发生这种情况是因为 as
运算符被定义为将对象转换为给定类型并在转换失败时崩溃。在这种情况下,对 dequeue
的调用在您第一次调用它时返回 nil
。您需要使用 as?
运算符,它将尝试将给定对象转换为一个类型,并返回一个只有在转换成功时才具有值的可选值:
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellId) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellId)
}
...
因为 cell
现在是一个可选值,所以当你想调用它的方法来强制展开里面的 UITableViewCell
时,使用 cell!
此外,您的代码还有第二个问题:它从未创建新的单元格。 dequeue
第一次在您的 TableView 上调用时将返回 nil。您需要像我的代码示例中那样实例化一个新的 UITableViewCell
,然后从 cellFor...
方法返回它。然后 TableView 将保存单元格并在以后调用 dequeue
时返回它。
关于uitableview - 启动应用程序 xCode 时的 EXC_BAD_INSTRUCTION 断点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24718135/