您好,我目前正在使用核心数据框架开发基于表格 View 的 iPhone 应用程序。到目前为止进展顺利,但我正在努力解决一个非常简单的问题。我刚刚开始学习 Swift,正在尝试自学以及开发一些有用的东西。我已经成功地用核心数据数据库中的数据填充了一个 TableView 。但是,我正在努力从数据源和 tabe View 中删除行。
这是我当前正在尝试的代码:
override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
if editingStyle == .Delete {
println("Delete")
// Delete the row from the data source
context.deleteObject(myData.objectAtIndex(indexPath.row) as NSManagedObject)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
错误的屏幕截图:
有什么建议吗?
最佳答案
可选变量必须先解包,然后才能访问其成员。
有两种方法可以解包可选变量。
你可以用感叹号强制解包:
indexPath!.row
但是,如果 indexPath
(正在解包的任何变量)为 nil
,这将导致运行时异常。
或者您可以测试 nil
并在它不是 nil
时解包:
if let unwrappedIndexPath = indexPath {
// do something with unwrappedIndexPath.row
}
if let tv = tableView {
tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
关于ios - 从数据源中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24196098/