1.我们在 Company.xcdatamodeld 里面新建一张表 Department,里面添加几个字段。
图1
2.然后我们在Employee 表里面设置关联。
图23.最后我们生成模型文件,如图:
4.弄好这些后 我们来看看如何使用:
(1)首先创建上下文 这里就不多复述了 详见《CoreData 的简单使用__ 01》。
(2)然后我们来添加信息 两个员工,一个属于iOS 一个属于Android
-(void)addEmployee{
//创建两个部门ios android
Department *iosDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department"inManagedObjectContext:_context];
iosDepart.name=@"iOS";
iosDepart.departNo=@"0001";
iosDepart.createDate= [NSDatedate];
Department *andrDepart = [NSEntityDescription insertNewObjectForEntityForName:@"Department"inManagedObjectContext:_context];
andrDepart.name=@"android";
andrDepart.departNo=@"0002";
andrDepart.createDate= [NSDatedate];
//创建两个员工对象zhangsan属于ios部门lisi属于android部门
Employee *zhangsan = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"inManagedObjectContext:_context];
zhangsan.name=@"zhangsan";
zhangsan.height=@(1.90);
zhangsan.birthday= [NSDate date];
zhangsan.depart= iosDepart;
Employee *lisi = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"inManagedObjectContext:_context];
lisi.name=@"lisi";
lisi.height=@2.0;
lisi.birthday= [NSDate date];
lisi.depart= andrDepart;
//直接保存数据库
NSError*error =nil;
[_context save:&error];
if(error) {
NSLog(@"%@",error);
}
}
(3) 添加完信息后我们来读取下:
-(void)readEmployee {
// 1.FectchRequest抓取请求对象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 2.设置过滤条件
NSPredicate*pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"iOS"];
request.predicate= pre;
// 4.执行请求
NSError*error =nil;
NSArray*emps = [_context executeFetchRequest:requesterror:&error];
if(error) {
NSLog(@"error");
}
//NSLog(@"%@",emps);
//遍历员工
for(Employee*emp in emps) {
NSLog(@"名字%@部门%@",emp.name,emp.depart.name);
}
}
网友评论