首页 > 代码库 > 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);