添加增 和查询
//
// ViewController.swift
// CodeDtaMM
//
// Created by ray on 2021/2/14.
//
import CoreData
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if var model = self.getNewObj(mType: User.self) {
model.name = "Test123"
self.saveCoreDate(model: &model)
}
if let list = self.fetchCoreData(mType: User.self) {
for item in list {
print("item \(item.name)")
}
}
}
func getNewObj<T:NSManagedObject>(mType:T.Type)->T? {
let appDel = UIApplication.shared.delegate as! AppDelegate
//获取管理的上下文
let context = appDel.persistentContainer.viewContext
//创建一个实例并给属性赋值
let name = "\(mType.self)"
let model = NSEntityDescription.insertNewObject(forEntityName: name, into: context) as? T
return model
}
//添加数据
func saveCoreDate<T:NSManagedObject>( model:inout T){
//加载AppDelegate
let appDel = UIApplication.shared.delegate as! AppDelegate
//获取管理的上下文
let context = appDel.persistentContainer.viewContext
//保存数据
do {
try context.save()
print("保存成功")
}catch let error{
print("context can't save!, Error:\(error)")
}
}
func fetchCoreData<T:NSManagedObject>(mType:T.Type)->[T]?{
//加载AppDelegate
let appDel = UIApplication.shared.delegate as! AppDelegate
//获取管理的上下文
let context = appDel.persistentContainer.viewContext
// 声明数据请求实体
if let fetchRequest:NSFetchRequest<T> = mType.fetchRequest() as? NSFetchRequest<T> {
if let peopleList =
try? context.fetch(fetchRequest) {
return peopleList
}
}
return nil
// let predicate = NSPredicate(format:"id=1") //设置查询条件按照id查找不设置查询条件,则默认全部查找
// fetchRequest.predicate=predicate
//执行查询操作
// do {
// try context.save()
//
// print("保存成功")
//
// }catch let error{
// print("context can't save!, Error:\(error)")
//
// }
}
}
创建实体类的时候,不要勾选target
网友评论