在我的tableViewController我有以下。而我正在尝试删除一个项目。
var myData: Array<AnyObject> = []
override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellID: Nsstring = "Cell"
var Cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
var data: NSManagedobject = myData[indexPath.row] as NSManagedobject
Cell.textLabel?.text = data.valueForKeyPath("Name") as? String
return Cell
}
然后尝试删除我有。
override func tableView(tableView: (UITableView!),commitEditingStyle editingStyle: UITableViewCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let cellID: Nsstring = "Cell"
var Cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellID) as UITableViewCell
var data: NSManagedobject = myData[indexPath.row] as NSManagedobject
data.delete(0)
// Delete the row from the data source
//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
}
}
更新我的编码问题,执行swift和coredata中的数据删除。这个代码我结束了,工作。
override func tableView(tableView: UITableView,forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedobjectContext = appDel.managedobjectContext!
context.deleteObject(myData[indexPath.row] as NSManagedobject)
myData.removeAtIndex(indexPath.row)
context.save(nil)
//tableView.reloadData()
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation: .Fade)
default:
return
}
}
编辑上面的Swift 2.2和Xcode 7.3.1
override func tableView(tableView: UITableView,forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedobjectContext = appDel.managedobjectContext
context.deleteObject(myData[indexPath.row] )
myData.removeAtIndex(indexPath.row)
do {
try context.save()
} catch _ {
}
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation: .Fade)
default:
return
}
}
还需要这两行代码来纠正。
var myData: Array<AnyObject> = [] let managedobjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedobjectContext