IOS10新版coredata ---by talent.L

一.创建两个Model

Model.h

#import@interface Model : NSObject

@property(nonatomic,strong)NSString *name,*age;

@end

Model1.h

#import "Model.h"

#import "Entity+CoreDataClass.h"

@interface Model1 : NSObject

//单例类

+(instancetype)shareLoadData;

//添加数据

-(void)insertData:(Model *)myAu;

//修改数据

-(void)updateData;

//删除数据

-(void)deleteData:(Entity *)au;

//查询所有数据

-(NSArray *)getAllData;

@end

Model1.m

#import

#import "Model1.h"

#import "AppDelegate.h"

static Model1 *ld;

@implementation Model1

//单例类

+(instancetype)shareLoadData{

if (!ld) {

ld = [[Model1 alloc]init];

}

return ld;

}

+(instancetype)allocWithZone:(struct _NSZone *)zone{

if (!ld) {

ld = [super allocWithZone:zone];

}

return ld;

}

-(id)copy{

return self;

}

-(id)mutableCopy{

return self;

}

//增加

-(void)insertData:(Model *)myAu{

AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;

//创建一个实体对象

Entity *au = [NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];

//给实体对象复制

au.name = myAu.name;

au.age = myAu.age;

//保存 (增删改)

[app saveContext];

}

//修改数据

-(void)updateData{

AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;

//保存 (增删改)

[app saveContext];

}

//删除数据

-(void)deleteData:(Entity *)au{

AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;

//删除信息

[app.persistentContainer.viewContext deleteObject:au];

//保存 (增删改)

[app saveContext];

}

//查询所有数据

-(NSArray *)getAllData{

AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;

//初始化一个抓取请求的对象

NSFetchRequest *request =[[NSFetchRequest alloc]init];

//初始化一个实体

NSEntityDescription *newAu = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:app.persistentContainer.viewContext];

//设置抓取请求

[request setEntity:newAu];

//查询数据

NSArray *arr = [app.persistentContainer.viewContext executeFetchRequest:request error:nil];

return arr;

}

@end

你可能感兴趣的:(IOS10新版coredata ---by talent.L)