比如企业下有众多部门,而员工属于某一个部门,则在员工表与部门表之间产生了关联。
在上一篇文章中已经有一张“Person”表了,现在创建一个“国家”表“Country”
然后把person类都删掉,重新生成一下person类文件。
重新生成后,就可以发现多出了关联的那个属性了。
- (void)addPersonAndCountry{
Person* person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Country"];
NSPredicate* predicate = nil;
if (arc4random()%2) {
predicate = [NSPredicate predicateWithFormat:@"name=%@",@"NaiCha"];
}else{
predicate = [NSPredicate predicateWithFormat:@"name=%@",@"KeKoCola"];
}
request.predicate = predicate;
//创建一个数组用于接收查询到的数据对象
NSError* error = nil;
NSArray* resultArray = [self.context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"查询失败,错误信息:%@",error);
}else{
if (resultArray.count == 1) {
Country* country = resultArray[0];
//给该模型对象赋值
int numberID = arc4random()%10000;
person.name = [NSString stringWithFormat:@"personSomeone%d",numberID];
int64_t personAge = arc4random()%100;
person.age = personAge;
person.country = country;
[self.context save:&error];
if (error) {
NSLog(@"添加个人信息出错,错误:%@",error);
}else{
NSLog(@"添加个人信息:%@-%lld-%@",person.name,person.age,person.country.name);
}
}else{
NSLog(@"查询无此国籍,无法添加个人信息");
}
}
}
运行结果:
2022-03-04 21:19:48.855904+0800 CoreData实践1[77919:3270501] 添加个人信息:personSomeone6740-84-KeKoCola
不用写任何数据库 *** 作的代码,直接将关联的对象当作属性成员赋值就完成关联了,非常方便。
查找关联数据- (void)findSomebodyByCountry:(NSString*)countryName{
//查找国籍为“奶茶”的人
NSFetchRequest* request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"country.name=%@",countryName];
request.predicate = predicate;
NSError* error = nil;
NSArray* resultArray = [self.context executeFetchRequest:request error:&error];
if (error) {
NSLog(@"查询失败,错误信息:%@",error);
}else{
NSLog(@"查询国籍为:%@的结果如下",countryName);
for (Person* person in resultArray) {
NSLog(@"name:%@ age:%lld country:%@",person.name,person.age,person.country.name);
}
}
}
运行结果:
2022-03-04 23:17:51.282876+0800 CoreData实践1[78883:3309210] 查询国籍为:NaiCha的结果如下
2022-03-04 23:17:51.283777+0800 CoreData实践1[78883:3309210] name:personSomeone8102 age:43 country:NaiCha
2022-03-04 23:17:51.283962+0800 CoreData实践1[78883:3309210] name:personSomeone5777 age:17 country:NaiCha
2022-03-04 23:17:51.284096+0800 CoreData实践1[78883:3309210] name:personSomeone966 age:17 country:NaiCha
2022-03-04 23:17:51.284221+0800 CoreData实践1[78883:3309210] name:personSomeone7477 age:57 country:NaiCha
2022-03-04 23:17:51.284329+0800 CoreData实践1[78883:3309210] name:personSomeone701 age:12 country:NaiCha
2022-03-04 23:17:51.284435+0800 CoreData实践1[78883:3309210] name:personSomeone2071 age:47 country:NaiCha
2022-03-04 23:17:51.284553+0800 CoreData实践1[78883:3309210] name:personSomeone1474 age:78 country:NaiCha
直接使用点语法增加书写约束语句即可实现关联数据的查询。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)