CoreData查询常见用法

来源:互联网 发布:ubuntu安装tftp服务器 编辑:程序博客网 时间:2024/06/05 09:52

- (IBAction)searchClick:(id)sender {

    

    //1. 创建查询请求

    NSFetchRequest *fetchRequest = [[NSFetchRequestalloc] init];

    

    //2. 创建实体描述 -->表名

    NSEntityDescription *entity = [NSEntityDescriptionentityForName:@"Person"inManagedObjectContext:HMManagerContext];

    [fetchRequest setEntity:entity];

    

    //3. 谓词 -->查询条件

//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"height>175"];

//    [fetchRequest setPredicate:predicate];

    

    //4. 排序描述 -->可以增加多个

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptoralloc] initWithKey:@"position"ascending:YES];

    

    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptoralloc] initWithKey:@"age"ascending:NO];

    [fetchRequest setSortDescriptors:[NSArrayarrayWithObjects:sortDescriptor,sortDescriptor2,nil]];

    

    //5. 执行查询请求

    NSError *error =nil;

    NSArray *fetchedObjects = [HMManagerContextexecuteFetchRequest:fetchRequesterror:&error];

    

    //6. 未查询到数据

    if (fetchedObjects ==nil) {

        NSLog(@"error: %@", error);

        return;

    }

    

    for (Person *pin fetchedObjects) {

        NSLog(@"Person: %@, %@, %zd, %zd", p.name, p.position, p.age, p.height);

    }

}

原创粉丝点击