1.我們在 Company.xcdatamodeld 里面新建一張表 Department,里面添加幾個字段。
2.然后我們在Employee 表里面設(shè)置關(guān)聯(lián)。
3.最后我們生成模型文件,如圖:
4.弄好這些后 我們來看看如何使用:
(1)首先創(chuàng)建上下文 這里就不多復(fù)述了 詳見《CoreData 的簡單使用__ 01》。
(2)然后我們來添加信息 兩個員工,一個屬于iOS 一個屬于Android
-(void)addEmployee{
//創(chuàng)建兩個部門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];
//創(chuàng)建兩個員工對象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;
//直接保存數(shù)據(jù)庫
NSError*error =nil;
[_context save:&error];
if(error) {
NSLog(@"%@",error);
}
}
(3) 添加完信息后我們來讀取下:
-(void)readEmployee {
// 1.FectchRequest抓取請求對象
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Employee"];
// 2.設(shè)置過濾條件
NSPredicate*pre = [NSPredicate predicateWithFormat:@"depart.name = %@",@"iOS"];
request.predicate= pre;
// 4.執(zhí)行請求
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);
}
}