首页 > 代码库 > CoreData用法四:多表查询
CoreData用法四:多表查询
首先介绍下表结构:目前有两张表,一张是student,一张是Teacher。其中student对teacher是多对一关系:
下面是添加的数据:
-(IBAction)add:(id)sender { Teacher * tea = (Teacher *)[NSEntityDescription insertNewObjectForEntityForName:@"Teacher" inManagedObjectContext:[CoreDataManage GetManagedObjectContext]]; tea.teachernumber = [NSNumber numberWithInt:1]; tea.name = @"王莹"; tea.age = [NSNumber numberWithInt:24]; tea.studentnumber = [NSNumber numberWithInt:1]; NSError * errorTemp = nil; if ([[CoreDataManage GetManagedObjectContext] save:&errorTemp]) { NSLog(@"===errorTemp===%@",errorTemp); } NSLog(@"===errorTemp===%@",errorTemp); Student * stu = (Student *)[NSEntityDescription insertNewObjectForEntityForName:TABLE_NAME inManagedObjectContext:[CoreDataManage GetManagedObjectContext]]; stu.studentnumber = [NSNumber numberWithInt:[self.tf_studentnumber.text intValue]]; stu.name = self.tf_name.text; stu.age = [NSNumber numberWithInt:[self.tf_age.text intValue]]; stu.gender=[NSNumber numberWithInt:[self.tf_gender.text intValue]]; NSError * error = nil; if ([[CoreDataManage GetManagedObjectContext] save:&error]) { self.tf_studentnumber.text = @""; self.tf_name.text = @""; self.tf_age.text = @""; self.tf_gender.text = @""; } else { NSLog(@"add entity error = %@",error); } }
查询学生名字为“jijunyuan”对应的老师的名字:
NSEntityDescription * emEty = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:[CoreDataManage GetManagedObjectContext]]; NSFetchRequest *frq = [[NSFetchRequest alloc] init]; [frq setEntity:emEty]; NSPredicate * cdt = [NSPredicate predicateWithFormat:@"studentnumber = %@",[NSNumber numberWithInt:1]]; [frq setPredicate:cdt]; NSArray *objs =[[CoreDataManage GetManagedObjectContext] executeFetchRequest:frq error:nil]; //NSLog(@"%i",[objs count]); Student * stu = (Student *)[objs objectAtIndex:0]; NSLog(@"====%@=========%@",stu.name,stu.teschership.name);
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。