CoreData実践(六)——データ削除
前のブログでCoreDataを使用して挿入、クエリー、更新操作を行う方法について説明しました.削除操作を実装しますが、削除操作は非常に簡単です.具体的には、次のようになります.
(1)UserTable ViewControllerで2つのメソッドを書き換え,具体的には以下のようにする.
(2)プログラムを実行し、cellを左にドラッグすると、1つのデータを削除できます.
githubホームページ:https://github.com/chenyufeng1991 .ようこそ!
(1)UserTable ViewControllerで2つのメソッドを書き換え,具体的には以下のようにする.
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を左にドラッグすると、1つのデータを削除できます.
githubホームページ:https://github.com/chenyufeng1991 .ようこそ!