Core Data

appdelegate里生成


    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded 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.
        */
        let container = NSPersistentContainer(name: "coreDataTest")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
                
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() 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
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

建模不多说 注意实例化对象出错的话clean强制退出,重新编译下

方法

//写入数据
    func insertClass(name: String, score: Double) {
        let context = appDelegate.persistentContainer.viewContext
        
        let people = People(context: context)
        
        people.name = name
        people.score = score
        
        print("正在保存")
        //保存对象实体
        
        appDelegate.saveContext()
    }


//读取所有数据(影响性能,不建议用)
    func fetchAllData() {
        
        var peoples : [People] = []
        
        do {
            peoples = try appDelegate.persistentContainer.viewContext.fetch(People.fetchRequest())
        } catch  {
            print(error)
        }
        
    }


//排序读取所有数据 (全局变量 var fc: NSFetchedResultsController!)
    func fetchData2() {
        //请求结果类型是People
        let request: NSFetchRequest = People.fetchRequest()
        //按照name升序
        let sd = NSSortDescriptor(key: "name", ascending: true)
        //NSSortDescriptor指定请求结果如何排序
        request.sortDescriptors = [sd]
        
        let context = appDelegate.persistentContainer.viewContext
        fc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        fc.delegate = self
        
        do {
            try fc.performFetch()
            if let objects = fc.fetchedObjects {
                peoples = objects
            }
        } catch {
            print(error)
        }
    }

//遵守NSFetchedResultsControllerDelegate代理,与tableview绑定
extension ViewController : NSFetchedResultsControllerDelegate {
    
    //当控制器开始处理内容变化时
    func controllerWillChangeContent(_ controller: NSFetchedResultsController) {
        tableview.beginUpdates()
    }
    //内容发生变更时
    func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
        switch type {
        case .delete:
            tableview.deleteRows(at: [indexPath!], with: .automatic)
        case .insert:
            tableview.insertRows(at: [newIndexPath!], with: .automatic)
        case .update:
            tableview.reloadRows(at: [indexPath!], with: .automatic)
        default:
            tableview.reloadData()
        }
        if let objects = controller.fetchedObjects {
            peoples = objects as! [People]
        }
    }
    //当控制器已经处理完变更时
    func controllerDidChangeContent(_ controller: NSFetchedResultsController) {
        tableview.endUpdates()
    }
}

//删除数据
  //按条删除
  let context = appDelegate.persistentContainer.viewContext
context.delete(self.fc.object(at: IndexPath))
appDelegate.saveContext()

  //删除2
    //删除数据
    func delData() {
        let context = appDelegate.persistentContainer.viewContext
        
        let request: NSFetchRequest = People.fetchRequest()
        
        let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: request) { (result:NSAsynchronousFetchResult) in
            
            //对返回的数据做处理。
            let fetchObject = result.finalResult!
            for c in fetchObject{
                
                //所有删除信息
                context.delete(c)
            }
            self.appDelegate.saveContext()
            
        }
        
        do {
            try context.execute(asyncFetchRequest)
        } catch  {
            print(error)
        }
    }

import UIKit

import CoreData

class ViewController: UIViewController {

    

    override func viewDidLoad() {

        super.viewDidLoad()

   }

}

 

 

 

//MARK: - CoreData

extension ViewController{

    

//MARK:    获取上下文对象

    func getContext() -> NSManagedObjectContext{

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        return appDelegate.persistentContainer.viewContext

        

    }

    

    

//MARK:    插入班级信息

    func insertClasses(){

        for i in 1...100{

            let classNO = Int64(i)

            let name = "rg"+"\(i)"

            insertClass(classno:classNO,name:name)

        }

    }

    func insertClass(classno:Int64,name:String) {

        //获取上下文对象

        let context = getContext()

        

//        //创建一个实例并赋值

//                let classEntity = NSEntityDescription.insertNewObject(forEntityName: "Class", into: context) as! Class

//

//        //Class对象赋值

//        classEntity.classNo = classno

//        classEntity.name = name

        

        

        //通过指定实体名 得到对象实例

        let Entity = NSEntityDescription.entity(forEntityName: "Class", in: context)

        let classEntity = NSManagedObject(entity: Entity!, insertInto: context)

        classEntity.setValue(classno, forKey: "classNo")

        classEntity.setValue(name, forKey: "name")

        do {

            //保存实体对象

            try context.save()

        } catch  {

            let nserror = error as NSError

            fatalError("错误:\(nserror),\(nserror.userInfo)")

        }

    }

    

 

//MARK:    查询班级信息

    func getClass(){

        

//        异步fetch

        

        //获取数据上下文对象

        let context = getContext()

        let fetchRequest = NSFetchRequest(entityName: "Class")

 

        // 异步请求由两部分组成:普通的request和completion handler

        // 返回结果在finalResult中

        let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result : NSAsynchronousFetchResult!) in

            

            //对返回的数据做处理。

            let fetchObject = result.finalResult as! [Class]

 

            for  c in fetchObject{

                print("\(c.classNo),\(c.name ?? "")")

            }

        }

        

        // 执行异步请求调用execute

        do {

            try context.execute(asyncFetchRequest)

   

        } catch  {

            print("error")

        }

 

    }

    

//MARK:    修改班级信息

    func modifyClass() {

        //获取委托

        let app = UIApplication.shared.delegate as! AppDelegate

        //获取数据上下文对象

        let context = getContext()

        //声明数据的请求,声明一个实体结构

        let fetchRequest = NSFetchRequest(entityName: "Class")

        //查询条件

        fetchRequest.predicate = NSPredicate(format: "classNo = 2", "")

        

        // 异步请求由两部分组成:普通的request和completion handler

        // 返回结果在finalResult中

        let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in

            

            //对返回的数据做处理。

            let fetchObject  = result.finalResult! as! [Class]

            for c in fetchObject{

                c.name = "qazwertdfxcvg"

                app.saveContext()

            }

        }

        

        // 执行异步请求调用execute

        do {

            try context.execute(asyncFecthRequest)

        } catch  {

            print("error")

        }

 

    }

    

//MARK:    删除班级信息

 

    func deleteClass() -> Void {

        //获取委托

        let app = UIApplication.shared.delegate as! AppDelegate

        

        //获取数据上下文对象

        let context = getContext()

       

        //声明数据的请求,声明一个实体结构

        let fetchRequest = NSFetchRequest(entityName: "Class")

        

        // 异步请求由两部分组成:普通的request和completion handler

        // 返回结果在finalResult中

        let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result:NSAsynchronousFetchResult) in

           

            //对返回的数据做处理。

            let fetchObject = result.finalResult! as! [Class]

            for c in fetchObject{

                

                //所有删除信息

                context.delete(c)

            }

             app.saveContext()

        }

        

          // 执行异步请求调用execute

        do {

            try context.execute(asyncFetchRequest)

        } catch  {

            print("error")

        }

    }

    

    //MARK:    统计信息

    func countClass() {

        //获取数据上下文对象

        let context = getContext()

        

        

        //声明数据的请求,声明一个实体结构

        let fetchRequest = NSFetchRequest(entityName: "Class")

        

        //请求的描述,按classNo 从小到大排序

        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "classNo", ascending: true)]

        

        //请求的结果类型

        //        NSManagedObjectResultType:返回一个managed object(默认值)

        //        NSCountResultType:返回满足fetch request的object数量

        //        NSDictionaryResultType:返回字典结果类型

        //        NSManagedObjectIDResultType:返回唯一的标示符而不是managed object

        fetchRequest.resultType = .dictionaryResultType

        

        // 创建NSExpressionDescription来请求进行平均值计算,取名为AverageNo,通过这个名字,从fetch请求返回的字典中找到平均值

        let description = NSExpressionDescription()

        description.name = "AverageNo"

        

        

        //指定要进行平均值计算的字段名classNo并设置返回值类型

        let args  = [NSExpression(forKeyPath: "classNo")]

        

        // forFunction参数有sum:求和 count:计算个数 min:最小值 max:最大值 average:平均值等等

        description.expression = NSExpression(forFunction: "average:", arguments: args)

        description.expressionResultType = .floatAttributeType

 

        // 设置请求的propertiesToFetch属性为description告诉fetchRequest,我们需要对数据进行求平均值

        fetchRequest.propertiesToFetch = [description]

        

        do {

            let entries =  try context.fetch(fetchRequest)

            let result = entries.first! as! NSDictionary

            let averageNo = result["AverageNo"]!

            print("\(averageNo)")

            

        } catch  {

            print("failed")

        }

    }

    

    

    //MARK:批量更新

    func batchUpdate()

    {

        let batchUpdate = NSBatchUpdateRequest(entityName: "Class")

        //所要更新的属性 和 更新的值

        batchUpdate.propertiesToUpdate = ["name": 55555]

        //被影响的Stores

        batchUpdate.affectedStores = self.getContext().persistentStoreCoordinator!.persistentStores

        //配置返回数据的类型

        batchUpdate.resultType = .updatedObjectsCountResultType

 

        //执行批量更新

        do {

           let batchResult = try getContext().execute(batchUpdate) as! NSBatchUpdateResult

        //批量更新的结果,上面resultType类型指定为updatedObjectsCountResultType,所以result显示的为 更新的个数

           print("\(batchResult.result!)")

        } catch   {

            print("error")

        }

    }

}

你可能感兴趣的:(Core Data)