//
// 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的使用
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- iOS Persistence and Core Data L3 - Udacity的笔记 笔记目录:1.保存数据...