ios - 从数据源中删除行

标签 ios xcode uitableview swift

您好,我目前正在使用核心数据框架开发基于表格 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
        }    
    }

错误的屏幕截图: enter image description here

有什么建议吗?

最佳答案

可选变量必须先解包,然后才能访问其成员。

有两种方法可以解包可选变量。

你可以用感叹号强制解包:

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/

相关文章:

ios - 从自定义 Cell 中正确委托(delegate)按钮操作以删除 UITableView 中的行

iphone - UIButton图像和视网膜显示

ios - 我可以将现有的 objective-C Today View 小部件转换为 iOS 14 主屏幕小部件吗?

android - 移植Android应用程序网站? (编辑: To any other platform?)

iphone - 重新加载数据时 tableView 会崩溃

ios - 我无法在 Swift 中删除我的最后一个表格 View 单元格

ios - 每次显示 UIViewController 时调用一个方法

ios - Sharekit Twitter 集成在 iOS 5 中崩溃

ios - 错误 : "A valid provisioning profile for this executable was not found"

ios - 用于通过终端进行分析的 Xcode 构建