swift 简单实现coreData数据库增删改查和关系表
import UIKit
import CoreData
class RootTableViewController: UITableViewController {
// TODO: 要做的事情
// FIXME: 要解决的BUG
var userDatas : NSMutableArray!
var context : NSManagedObjectContext!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGrayColor()
userDatas = NSMutableArray()
context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
self.readDatas()
let leftItem = UIBarButtonItem(title: "编辑", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("touchLeftButtonItem"))
self.navigationItem.leftBarButtonItem = leftItem
let rightItem = UIBarButtonItem(title: "增加", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("touchRightButtonItem"))
self.navigationItem.rightBarButtonItem = rightItem
let footerView = UIView()
footerView.backgroundColor = UIColor.clearColor()
self.tableView.tableFooterView = footerView
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userDatas.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let user = userDatas[indexPath.row] as! Users
cell.textLabel?.text = user.date
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
context.deleteObject(userDatas[indexPath.row] as! NSManagedObject)
do {
try context.save()
}catch {
let nserror = error as NSError
NSLog("删除 error \(nserror), \(nserror.userInfo)")
abort()
}
userDatas.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
// 修改操作
let row = userDatas[indexPath.row] as! Users
// row.date = "abcd"
row.setValue(self.getCurrentDateString(), forKey: "date")
do {
try row.managedObjectContext!.save()
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}catch {
let nserror = error as NSError
NSLog("修改 error \(nserror), \(nserror.userInfo)")
abort()
}
}
//MARK: - AllTouch事件
func touchLeftButtonItem() {
// 编辑
self.tableView.setEditing(!self.tableView.editing, animated: true)
}
func touchRightButtonItem() {
// 增加
if self.tableView.editing {
self.tableView.setEditing(false, animated: true)
}
let people: Peoples = NSEntityDescription.insertNewObjectForEntityForName("Peoples", inManagedObjectContext: context) as! Peoples
people.name = "张三"
people.age = 2
let row:Users = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as! Users
row.setValue(self.getCurrentDateString(), forKey: "date")
row.name = "李四"
row.people = people
do {
try context.save()
userDatas.addObject(row)
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: userDatas.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: userDatas.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
// self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Automatic)
} catch {
let nserror = error as NSError
NSLog("插入 error \(nserror), \(nserror.userInfo)")
abort()
}
}
//Mark: - 自定义方法
func readDatas() {
// 读取本地数据
let fetch = NSFetchRequest(entityName: "Users")
do {
let tempDatas = try context.executeFetchRequest(fetch)
if tempDatas.count > 0{
userDatas.addObjectsFromArray(tempDatas)
self.tableView.reloadData()
}
} catch{
let nserror = error as NSError
NSLog("读取 error \(nserror), \(nserror.userInfo)")
abort()
}
}
func getCurrentDateString() ->NSString{
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy年MM月dd日 HH时mm分ss秒"
let dateStr = formatter.stringFromDate(NSDate())
return dateStr
}
}
模版
import UIKit
import CoreData
class Users:NSManagedObject {
@NSManaged var date : String
@NSManaged var name : String
@NSManaged var people : Peoples
}
import UIKit
import CoreData
class Peoples: NSManagedObject {
@NSManaged var name : String
@NSManaged var age : Int32
@NSManaged var user : Users
}