您的位置:首页 > 其它

CoreData实践(六)——数据删除

2015-09-17 19:48 218 查看
     我在前面几篇博客讲到了如何使用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  。欢迎大家访问!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: