我们成功实现了从Core Data中保存和读取,但是当删除随机单元格时,我们在从Core Data中删除数据时遇到问题。 如何从tableView中删除随机单元格时从Core Data中删除数据???我们输入了一些代码,比如从数组中删除最后一个索引,但它不起作用......
2cd Vc
import UIKit
import CoreData
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var item = [NSManagedObject] ()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return item.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let person = item[indexPath.row]
cell.textLabel!.text = person.valueForKey("username") as? String
cell.detailTextLabel?.text = person.valueForKey("passwords") as? String
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// WHAT TO TYPE HERE TO REMOVE DATA FROM CORE DATA WHEN RANDOM CELL IS DELETED
let context: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
do {
try context.save()
} catch _ {
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Users")
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
item = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
答案 0 :(得分:0)
我发现它像这样工作
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(item[indexPath.row] as NSManagedObject)
item.removeAtIndex(indexPath.row)
do{
try context.save()
}catch{
print("Error, data not saved!")
}
//tableView.reloadData()
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}