2015-10-05 89 views
1

我们成功地实现了从Core Data中保存和读取数据,但是在随机单元格被删除时,我们在从Core Data中删除数据时遇到了问题。 当随机单元格从tableView中删除时如何从核心数据中删除数据?我们输入一些代码,就像从阵列中除去最后一个索引,但它不工作...Swift 2.0核心数据TableView删除单元格

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

我发现这样工作

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 

    }