【问题标题】:Delete the row from data source从数据源中删除行
【发布时间】:2014-06-13 00:43:10
【问题描述】:

您好,我目前正在使用核心数据框架开发基于表格视图的 iPhone 应用程序。到目前为止进展顺利,但我在一个非常简单的问题上苦苦挣扎。我刚刚学习了 Swift,我正在尝试自学并开发一些有用的东西。我已经成功地用核心数据数据库中的数据填充了一个表视图。但是,我正在努力从数据源和表视图中删除该行。

这是我目前正在尝试的代码:

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
        }    
    }

错误截图:

有什么建议吗?

【问题讨论】:

标签: ios xcode uitableview swift


【解决方案1】:

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

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

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

indexPath!.row

但是,如果 indexPath(正在解包的任何变量)是 nil,这将导致运行时异常。

或者您可以测试nil,如果不是nil,则解包:

if let unwrappedIndexPath = indexPath {
    // do something with unwrappedIndexPath.row
}

if let tv = tableView {
    tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}

【讨论】:

  • 如何解决我得到的第二个错误:'UITableView?'没有成员“deleteRowsAtIndexPaths”?
  • 以完全相同的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 2015-08-07
  • 2020-12-10
相关资源
最近更新 更多