CoreData實踐(六)——資料刪除

乞力馬紮羅的雪CYF發表於2015-09-17

     我在前面幾篇部落格講到了如何使用CoreData來進行插入,查詢,更新操作。現在我們將要實現刪除操作,其實刪除操作非常簡單。具體實現如下:

(1)在UserTableViewController中重寫兩個方法,具體實現如下:

import UIKit
import CoreData

class UsersTableViewController: UITableViewController {
  
  var dataArr:Array<AnyObject>! = []
  var context:NSManagedObjectContext!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    
    context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    
    refreshData()
    
    
  }
  
  // MARK: - Table view data source
  
  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
  }
  
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return dataArr.count
  }
  
  
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
    
    
    var name = dataArr[indexPath.row].valueForKey("name") as! String
    var age = dataArr[indexPath.row].valueForKey("age") as! Int
    
    var label = cell.viewWithTag(101) as! UILabel
    label.text = "姓名:\(name);  年齡:\(age)"
    
    
    
    
    return cell
  }
  
  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
    var data  = dataArr[indexPath.row] as! NSManagedObject
    
    var vc = storyboard?.instantiateViewControllerWithIdentifier("UserContent") as! UserContentViewController
    
    vc.data = data
    
    presentViewController(vc, animated: true, completion: nil)
    
  }
  
  
  func refreshData(){
    
    var f = NSFetchRequest(entityName: "Users")
    dataArr = context.executeFetchRequest(f, error: nil)
    
    tableView.reloadData()
    
  }
  
  override func viewWillAppear(animated: Bool) {
    refreshData()
  }
  
  
  override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    
    //這裡返回true,表示cell可以編輯;
    
    
    return true
  }
  
  override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    
    if editingStyle == UITableViewCellEditingStyle.Delete{
      
      context.deleteObject(dataArr[indexPath.row] as! NSManagedObject)
      
      //一定要執行儲存操作,否則不會刪除;
      context.save(nil)
      
      refreshData()
      
    }else if editingStyle == UITableViewCellEditingStyle.Insert{
      
      
    }
    
  }
  
}

(2)執行程式,向左拖動cell,就可以刪除一條資料。


github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章