iOS CoreData 增刪改查詳解

最近在學習CoreData, 因爲項目開發中需要,特意學習和整理了一下,整理出來方便以後使用和同行借鑑。目前開發使用的Swift語言開發的項目。所以整理出來的是Swift版本,OC我就放棄了。 雖然Swift3 已經有了,目前整理的這個版本是Swift2 的。Swift 3 的話有些新特性。 需要另外調整,後續有時間再整理。

繼承CoreData有兩種方式:

創建項目時集成

這種方式是自動繼承在AppDelegate裏面,調用的使用需要通過UIApplication的方式來獲取AppDelegate得到Conext。本人不喜歡這種方式,不喜歡AppDelegate太多代碼堆在一起,整理了一下這種方式

 

將CoreData繼承的代碼單獨解耦出來做一個單例類

項目結構圖

項目文件說明

CoreData核心的文件就是

1.XPStoreManager(管理CoreData的單例類)

2.CoredataDemo.xcdatamodeld (CoreData數據模型文件)

3.Student+CoreDataProperites.swift和Student.swift (學生對象)

4.ViewController.swift 和Main.storyboard是示例代碼

細節代碼

1. XPStoreManager.swift

CoreData數據管理單例類

//
//  XPStoreManager.swift
//  CoreDataDemo
//
//  Created by xiaopin on 16/9/16.
//  Copyright © 2016年 xiaopin.cnblogs.com. All rights reserved.
//

import CoreData

/// 本地數據庫管理類:默認是寫在AppDelegate的,可以這樣分離出來
class XPStoreManager {
    
    //單例寫法
    static let shareInstance = XPStoreManager()
    
    private init() {
        
    }
    
    // MARK: - Core Data stack
    
    lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.pinguo.CoreDataDemo" in the application's documents Application Support directory.
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        print("\(urls[urls.count-1])")
        return urls[urls.count-1]
    }()
    
    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = NSBundle.mainBundle().URLForResource("CoreDataDemo", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()
    
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason
            
            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()
    
    lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }
        }
    }
    
}

  

2.AppDelegate.swift

在這個行數中加入一句代碼,退出後執行保存一下

func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        XPStoreManager.shareInstance.saveContext()
    }

  

3.Student.swift

編寫了針對這個學生對象的增刪改查

//
//  Student.swift
//  CoreDataDemo
//
//  Created by cdmac on 16/9/12.
//  Copyright © 2016年 xiaopin.cnblogs.com. All rights reserved.
//

import Foundation
import CoreData

class Student: NSManagedObject {
    // Insert code here to add functionality to your managed object subclass
    /*
     一般涉及到的情況有:增刪改,單對象查詢,分頁查詢(所有,條件查詢,排序),對象是否存在,批量增加,批量修改
     */
    
    /// 判斷對象是否存在, obj參數是當前屬性的字典
    class func exsitsObject(obj:[String:String]) -> Bool {
        
        //獲取管理數據對象的上下文
        let context = XPStoreManager.shareInstance.managedObjectContext
        //聲明一個數據請求
        let fetchRequest = NSFetchRequest(entityName: "Student")
        
        //組合過濾參數
        let stuId = obj["stuId"]
        let name = obj["name"]
        
        //方式一
        let predicate1 = NSPredicate(format: "stuId = %@", stuId!)
        let predicate2 = NSPredicate(format: "name = %@", name!)
        //合成過濾條件
        //or ,and, not , 意思是:或與非,懂數據庫的同學應該就很容易明白
        let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1,predicate2])
        //let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2])
        fetchRequest.predicate = predicate
        
        //方式二
        //fetchRequest.predicate = NSPredicate(format: "stuId = %@ or name = %@", stuId!, name!)
        //fetchRequest.predicate = NSPredicate(format: "stuId = %@ and name = %@", stuId!, name!)
        
        do{
            let fetchObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
            
            return fetchObjects?.count > 0 ? true : false
        }catch {
            fatalError("exsitsObject \(error)")
        }
        
        return false
    }
    
    /// 添加對象, obj參數是當前屬性的字典
    class func insertObject(obj: [String:String]) -> Bool {
        
        //如果存在對象了就返回
        if exsitsObject(obj) {
            return false
        }
        
        //獲取管理的數據上下文 對象
        let context = XPStoreManager.shareInstance.managedObjectContext
        
        //創建學生對象
        let stu = NSEntityDescription.insertNewObjectForEntityForName("Student",
                                                                       inManagedObjectContext: context) as! Student

        //對象賦值
        let sexStr:String
        if obj["sex"] == "男"{
            sexStr = "1"
        }else{
            sexStr = "0"
        }
        let numberFMT = NSNumberFormatter()
        numberFMT.numberStyle = .NoStyle
        stu.stuId = numberFMT.numberFromString(obj["stuId"]!)
        stu.name = obj["name"]
        stu.createtime = NSDate()
        stu.sex = numberFMT.numberFromString(sexStr)
        stu.classId = numberFMT.numberFromString(obj["classId"]!)
        
        //保存
        do {
            try context.save()
            print("保存成功!")
            return true
        } catch {
            fatalError("不能保存:\(error)")
        }
        return false
    }
    
    /// 刪除對象
    class func deleteObject(obj:Student) -> Bool{
        
        //獲取管理的數據上下文 對象
        let context = XPStoreManager.shareInstance.managedObjectContext
        
        //方式一: 比如說列表已經是從數據庫中獲取的對象,直接調用CoreData默認的刪除方法
        context.deleteObject(obj)
        XPStoreManager.shareInstance.saveContext()
        
        //方式二:通過obj參數比如:id,name ,通過這樣的條件去查詢一個對象一個,把這個對象從數據庫中刪除
        //代碼:略
        
        return true
    }
    
    /// 更新對象
    class func updateObject(obj:[String: String]) -> Bool {
        //obj參數說明:當前對象的要更新的字段信息,唯一標誌是必須的,其他的是可選屬性
        let context = XPStoreManager.shareInstance.managedObjectContext
        
        let oid = obj["stuId"]
        let student:Student = self.fetchObjectById(Int(oid!)!)! as! Student
        
        //遍歷參數,然後替換相應的參數
        let numberFMT = NSNumberFormatter()
        numberFMT.numberStyle = .NoStyle
        
        for key in obj.keys {
            switch key {
            case "name":
                student.name = obj["name"]
            case "classId":
                student.classId = numberFMT.numberFromString(obj["classId"]!)
            default:
                print("如果有其他參數需要修改,類似")
            }
        }
        
        //執行更新操作
        do {
            try context.save()
            print("更新成功!")
            return true
        } catch {
            fatalError("不能保存:\(error)")
        }
        
        return false
    }
    
        /// 查詢對象
    class func fetchObjects(pageIndex:Int, pageSize:Int) -> [AnyObject]? {
        //獲取管理的數據上下文 對象
        let context = XPStoreManager.shareInstance.managedObjectContext
        
        //聲明數據的請求
        let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Student")
        fetchRequest.fetchLimit = pageSize //每頁大小
        fetchRequest.fetchOffset = pageIndex * pageSize //第幾頁
        
        //設置查詢條件:參考exsitsObject
        //let predicate = NSPredicate(format: "id= '1' ", "")
        //fetchRequest.predicate = predicate
        
        //設置排序
        //按學生ID降序
        let stuIdSort = NSSortDescriptor(key: "stuId", ascending: false)
        //按照姓名升序
        let nameSort = NSSortDescriptor(key: "name", ascending: true)
        let sortDescriptors:[NSSortDescriptor] = [stuIdSort,nameSort]
        fetchRequest.sortDescriptors = sortDescriptors
        
        //查詢操作
        do {
            let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
            
            //遍歷查詢的結果
            /*
            for info:Student in fetchedObjects as! [Student]{
                print("id=\(info.stuId)")
                print("name=\(info.name)")
                print("sex=\(info.sex)")
                print("classId=\(info.classId)")
                print("createTime=\(info.createtime)")
                print("-------------------")
                
            }
             */
            return fetchedObjects
        }
        catch {
            fatalError("不能保存:\(error)")
        }
        return nil
    }
    
        /// 根據ID查詢當個對象
    class func fetchObjectById(oid:Int) -> AnyObject?{
        
        //獲取上下文對象
        let context = XPStoreManager.shareInstance.managedObjectContext
        
        //創建查詢對象
        let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "Student")
        
        //構造參數
        fetchRequest.predicate = NSPredicate(format: "stuId = %@", String(oid))
        
        //執行代碼並返回結果
        do{
            let results:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
            
            if results?.count > 0 {
                return results![0]
            }
        }catch{
            fatalError("查詢當個對象致命錯誤:\(error)")
        }
        
        return nil
    }
}

  

4.ViewController.swift

具體使用:

//
//  ViewController.swift
//  CoreDataDemo
//
//  Created by cdmac on 16/9/11.
//  Copyright © 2016年 pinguo. All rights reserved.
//

import UIKit

let cellIdentifiler = "ReuseCell"

class ViewController: UIViewController {
    @IBOutlet weak var txtNo: UITextField!
    @IBOutlet weak var txtName: UITextField!
    @IBOutlet weak var txtSex: UITextField!
    @IBOutlet weak var txtClassId: UITextField!
    @IBOutlet weak var tableView: UITableView!
    var dataArray:[AnyObject]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.dataArray = Student.fetchObjects(0, pageSize: 20)
        self.tableView.reloadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func addAction(sender: AnyObject) {

        var dic = [String:String]()
        
        dic["stuId"] = txtNo.text
        dic["name"] = txtName.text
        dic["sex"] = txtSex.text
        dic["classId"] = txtClassId.text
        
        if Student.insertObject(dic) {
            print("添加成功")
            self.dataArray = Student.fetchObjects(0,pageSize: 20)
            
            self.tableView.reloadData()
        }else{
            print("添加失敗")
        }
    }
    
    @IBAction func updateAction(sender: AnyObject) {
        
        var dic = [String:String]()
        
        dic["stuId"] = txtNo.text
        dic["name"] = txtName.text
        //dic["sex"] = txtSex.text
        dic["classId"] = txtClassId.text
        
        if Student.updateObject(dic) {
            print("更新成功")
            self.dataArray = Student.fetchObjects(0,pageSize: 20)
            
            self.tableView.reloadData()
        }else{
            print("更新失敗")
        }
        
    }
    
}

extension ViewController:UITableViewDelegate,UITableViewDataSource{
    
    //表格有多少組
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    //每組多少行
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.dataArray != nil && self.dataArray?.count > 0 {
            return self.dataArray!.count
        }
        return 0
    }
    
    //高度
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 50
    }
    
    //單元格加載
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifiler)
        
        let stu:Student = self.dataArray![indexPath.row] as! Student
        
        let label1:UILabel = cell?.contentView.viewWithTag(10001) as! UILabel
        let label2:UILabel = cell?.contentView.viewWithTag(10002) as! UILabel
        var sexStr = "男"
        if stu.sex?.intValue != 1 {
            sexStr = "女"
        }
        label1.text = "\(stu.stuId!) \(stu.name!) \(sexStr) \(stu.classId!)"
        label2.text = "http://xiaopin.cnblogs.com"
        
        return cell!
    }
    
    //選中
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
    }
    
    func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            //獲取當前對象
            let student:Student = self.dataArray![indexPath.row] as! Student
            
            //刪除本地存儲
            Student.deleteObject(student)
            
            //刷新數據源
            self.dataArray?.removeAtIndex(indexPath.row)
            //self.dataArray = Student.fetchObjects(0, pageSize: 20)
            
            //刪除單元格
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        }
    }
    
    func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        return .Delete
    }
    
    func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? {
        return "刪除"
    }
}

  

運行效果圖

源碼下載:CoreDataDemo.zip

 

原創文章,轉載請著名出處!謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章