从Coredata Swift删除数据

在我的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, commitEditingStyle editingStyle: UITableViewCellEditingStyle, 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

}

}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, 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

以上是 从Coredata Swift删除数据 的全部内容, 来源链接: utcz.com/qa/420457.html

回到顶部