美文网首页Swift
Core Data的使用

Core Data的使用

作者: 王勋才 | 来源:发表于2021-11-28 21:07 被阅读0次
//
//  CoreDataManager.swift

//
//  Created by wangxuncai on 2021/11/27.
//

import Foundation
import CoreData
import UIKit

//Core data
class CoreDataManager{
    static let instance = CoreDataManager() //单例
    let container:NSPersistentContainer
    let context:NSManagedObjectContext
    init(){
        container = NSPersistentContainer(name: "DataManagerCoreData")
        container.loadPersistentStores { description, error in
            if let error = error {
                print("加载core data 失败 :\(error.localizedDescription)")
            }
        }
        context = container.viewContext
    }
    func save(){
        do {
            try context.save()
             print("保存成功!")
        } catch let error {
            print(" 保存core data失败 :\(error.localizedDescription) ")
        }
    }
    
}

//Model
class CoreDataViewModel:ObservableObject{
    let manager = CoreDataManager.instance
    @Published var students:[Student] = []
    init(){
        getStudents()
    }
    //给指定学生添加 照片
    func add(image:UIImage,to student:Student){
        let newPhoto = Photo(context: manager.context)
        newPhoto.image = image.data
        newPhoto.student = student
        save()
     getStudents()
    }
    func addStudent(name:String,classID:String,image:UIImage){
        let newStudent = Student(context: manager.context)
            newStudent.id = UUID()
            newStudent.name = name
            newStudent.classID = classID
        if image != UIImage(){
            newStudent.photo = image.data
        }
          
        //newStudent.recordInWord = ["没写好"]
          
           save()
        getStudents()
        
       
    }
    
    func deleteAllStudent(){
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: manager.context)
        let request = NSFetchRequest<Student>(entityName: "Student")
        //可以对request 进行修饰
       // request.fetchLimit = 10
      //  request.fetchOffset = 1
       request.entity = entity
        //根据谓词进行查询
      //  let predicate = NSPredicate(format: "name= 'Mike'", "")
      //  request.predicate = predicate
        do {
            let   students:[AnyObject]? =  try manager.context.fetch(request)
            for student:Student in students as! [Student] {
          
                    //删除
                    manager.context.delete(student)
                    print("删除成功")
                   
        
            }
            save()
            getStudents()
        } catch let error {
            print("获取所有学生数据失败。错误信息: \(error.localizedDescription)")
        }
    }
    func deleteStudent(byID:String){
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: manager.context)
        let request = NSFetchRequest<Student>(entityName: "Student")
        //可以对request 进行修饰
       // request.fetchLimit = 10
      //  request.fetchOffset = 1
       request.entity = entity
        //根据谓词进行查询
      //  let predicate = NSPredicate(format: "name= 'Mike'", "")
      //  request.predicate = predicate
        do {
            let   students:[AnyObject]? =  try manager.context.fetch(request)
            for student:Student in students as! [Student] {
                //在这里修改
                
                if student.classID == byID{
                    //删除
                    manager.context.delete(student)
                    print("删除成功")
                    save()
                }
              
              
               
            }
            getStudents()
        } catch let error {
            print("获取所有学生数据失败。错误信息: \(error.localizedDescription)")
        }
    }
    func update(){
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: manager.context)
        let request = NSFetchRequest<Student>(entityName: "Student")
        //可以对request 进行修饰
       // request.fetchLimit = 10
      //  request.fetchOffset = 1
       request.entity = entity
        //根据谓词进行查询
        let predicate = NSPredicate(format: "name= 'Mike'", "")
        request.predicate = predicate
        do {
            let   students:[AnyObject]? =  try manager.context.fetch(request)
            for student:Student in students as! [Student] {
                //在这里修改
                if student.classID == "1"{
                    //do sth
                }
                student.name = "wangxuncai"
                save()
            }
        } catch let error {
            print("获取所有学生数据失败。错误信息: \(error.localizedDescription)")
        }
    }
    func getStudents(){
        //描述一下 实体的名字,在哪个上下文
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: manager.context)
        //建立一个请求
        let request = NSFetchRequest<Student>(entityName: "Student")
       // request.fetchOffset = 0
      //  request.fetchLimit = 10
        request.entity = entity
        do {
          students =  try manager.context.fetch(request)
        } catch let error {
            print("获取所有学生数据失败。错误信息: \(error.localizedDescription)")
        }
        
    }
 
    
    func add(image:UIImage,student:Student){
        if  let data = image.jpegData(compressionQuality: 0){
           // student.recordInPhoto = [data]
        } else if let data = image.pngData(){
          //  student.recordInPhoto = [data]
        }else{
            print("保存照片失败")
        }
        save()
    }
    
    func add(content:String,student:Student){
        //student.recordInWord = [content]
        save()
    }
    
    func save(){
        manager.save()
    }
}
苹果应用商店|搜|王勋才|有我全部作品

相关文章

网友评论

    本文标题:Core Data的使用

    本文链接:https://www.haomeiwen.com/subject/chbhxrtx.html