iOS:CoreData數據持久化

#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;

#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];

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章