数据库

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值