DataManager.h
#import <Foundation/Foundation.h>
#import "Student+CoreDataClass.h"
#import "Model.h"
NS_ASSUME_NONNULL_BEGIN
@interface DataManager : NSObject
+(DataManager *)shareManager;
-(void)insert:(NSDictionary *)dic;
-(void)update:(Student *)student;
-(void)deleteData:(Student *)student;
-(NSArray *)select;
@end
NS_ASSUME_NONNULL_END
DataManager.m
#import "DataManager.h"
#import "AppDelegate.h"
#import "Model.h"
@interface DataManager(){
//声明一个APPdelegate对象属性,调用里面的被管理对象上下文 保存方法
AppDelegate *myDelegate;
}
@end
@implementation DataManager
+(DataManager *)shareManager{
static DataManager *manager;
if (!manager) {
manager = [[DataManager alloc] init];
}
return manager;
}
-(void)insert:(NSDictionary *)dic{
//coreData 数据的插入
myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//创建实体描述对象
NSEntityDescription * description = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:myDelegate.persistentContainer.viewContext];
//创建一个模型对象
Student * student = [[Student alloc]initWithEntity:description insertIntoManagedObjectContext:myDelegate.persistentContainer.viewContext];
student.name = dic[@"name"];
student.create_time = dic[@"create_time"];
student.describe = dic[@"describe"] ;
student.start_time = dic[@"start_time"];
student.type = dic[@"type"];
//对数据管理器的更改进行永久保存
[myDelegate saveContext];
}
-(NSArray *)select{
myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//查询数据
// (1) 设置需要抓取的实体类
NSEntityDescription *selectEneity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:myDelegate.persistentContainer.viewContext];
// (2)实例化抓取对象
NSFetchRequest *req = [[NSFetchRequest alloc] init];
// (3)设置抓取
[req setEntity:selectEneity];
// (4)获取抓取结果
NSArray *res = [myDelegate.persistentContainer.viewContext executeFetchRequest:req error:nil];
return res;
}
-(void)update:(Student *)student{
myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[myDelegate saveContext];
}
-(void)deleteData:(Student *)student{
myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
[myDelegate.persistentContainer.viewContext deleteObject:student];
[myDelegate saveContext];
}
@end