CoreData查询常见用法

本文介绍如何使用 Core Data 进行数据查询,包括创建查询请求、设置实体描述、定义查询条件及排序方式等步骤,并展示了查询结果的处理方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

- (IBAction)searchClick:(id)sender {

    

    //1. 创建查询请求

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    

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

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

    [fetchRequest setEntity:entity];

    

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

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

//    [fetchRequest setPredicate:predicate];

    

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

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

    

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

    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor,sortDescriptor2, nil]];

    

    //5. 执行查询请求

    NSError *error = nil;

    NSArray *fetchedObjects = [HMManagerContext executeFetchRequest:fetchRequest error:&error];

    

    //6. 未查询到数据

    if (fetchedObjects == nil) {

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

        return;

    }

    

    for (Person *p in fetchedObjects) {

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

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值