swift Core Data 简单使用

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

1.创建Core Data

创建完后,我们就能看到类似的页面。

Add Entity,添加一个主体,里面可以添加响应的属性,和主体之间依赖关系。我们也可以理解为这是一个类。

2.设置管理和持久化应用对象的类

在appdelegate中创建 NSPersistentContainer

    lazy var persistentContainer: NSPersistentContainer = {
        //名字和Model.xcdatamodeld一样
        let container = NSPersistentContainer(name: "Model")
        //本地持久化资源的加载
        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError("Unable to load persistent stores: \(error)")
            }
        }
        return container
    }()

    
    // MARK: - Core Data Saving support
    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
复制代码

显示持久容器实例包含对托管对象模型、托管对象上下文和连接到应用商店的持久存储协调器的引用的图表。

3.添加数据

主要用的是insertNewObject

//    创建一个学生身份
    static func createStudent(name: String, sid: String, age: Int, block:()->Void) {
        //获取管理的数据上下文 对象
        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        // 插入数据
        let stu = NSEntityDescription.insertNewObject(forEntityName: "Student", into: context) as! Student
        let teacher = NSEntityDescription.insertNewObject(forEntityName: "Teacher", into: context) as! Teacher
        teacher.name = "xiaowen"
        teacher.job = "语文"
        
        stu.name = name
        stu.sid = sid
        stu.age = Int16(age)
        
        stu.teachBy = teacher
        
        if context.hasChanges {
            do {
                // 保存数据
                try context.save()
                print("Insert new stu(\(name)) successful.")
                block()
            } catch {
                print(error)
            }
        }
    }
复制代码

4.查询数据

查询数据用的是NSFetchRequest

 //    查询学生通过名字
    static func queryStudentWithName(_ name: String ) {
        //获取管理的数据上下文 对象
        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        // 查询数据
        let fetchStudents = NSFetchRequest<Student>.init(entityName: "Student")
        // 条件查询
        fetchStudents.predicate = NSPredicate(format: "name = \"\(name)\"")

        do {
            let students = try context.fetch(fetchStudents)
            print("students count = \(students.count)")
            for student in students {
                print("student name = \(student.name!)")
            }
            print("query student:\(name) successful.")
        } catch {
            
        }
    }
复制代码

5.修改数据

流程主要是读取→修改→保存

//    修改一个学生的名字 读取→修改→保存
    static func updateStudentWithName(_ name: String, newName: String) {
        //获取管理的数据上下文 对象
        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        // 查询数据
        let fetchStudents = NSFetchRequest<Student>.init(entityName: "Student")
        // 条件查询
        fetchStudents.predicate = NSPredicate(format: "name = \"\(name)\"")
        
        do {
            let students = try context.fetch(fetchStudents)
            if !students.isEmpty {
                students[0].name = newName
                if context.hasChanges {
                    do {
                        // 保存数据
                        try context.save()
                        print("Update new Student successful.")
                    } catch {
                        print(error)
                    }
                }
            }
        } catch {
            
        }
    }
复制代码

6.删除数据

流程主要是读取→删除→保存。

 //    删除一个学生通过名字 读取→删除→保存
    static func deleteStudentWithName(_ name: String) {
        //获取管理的数据上下文 对象
        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        // 查询数据
        let fetchStudents = NSFetchRequest<Student>.init(entityName: "Student")
        // 条件查询
        fetchStudents.predicate = NSPredicate(format: "name = \"\(name)\"")
        
        do {
            let students = try context.fetch(fetchStudents)
            if !students.isEmpty {
                context.delete(students[0])
                if context.hasChanges {
                    do {
                        // 保存数据
                        try context.save()
                        print("delete \(name) successful.")
                    } catch {
                        print(error)
                    }
                }
            }
        } catch {
            
        }
    }
复制代码

gitHub源码:github.com/wenweijia/C…

猜你喜欢

转载自juejin.im/post/7013631986484903967