swift 简单实现coreData数据库增删改查和关系表

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
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值