码迷,mamicode.com
首页 > 其他好文 > 详细

CoreData用法四:多表查询

时间:2014-06-20 09:02:15      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   http   

首先介绍下表结构:目前有两张表,一张是student,一张是Teacher。其中student对teacher是多对一关系:

bubuko.com,布布扣


下面是添加的数据:

-(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);






CoreData用法四:多表查询,布布扣,bubuko.com

CoreData用法四:多表查询

标签:des   style   class   blog   code   http   

原文地址:http://blog.csdn.net/jijunyuan/article/details/28330415

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!