OC-简单的介绍谓词和使用方法

本文通过实例演示如何使用 NSPredicate 对 Person 对象数组进行多种条件筛选,包括年龄、姓名等属性的精确匹配与模糊匹配。
 /*NSPredicate 指定条件过滤数据*/
    
    
    Person *person1 = [[Person alloc] initPerson:@"张三" age:12];
    Person *person2 = [[Person alloc] initPerson:@"李四" age:21];
    Person *person3 = [[Person alloc] initPerson:@"王五" age:33];
    Person *person4 = [[Person alloc] initPerson:@"赵六" age:15];
    
    NSArray *storage = [NSArray arrayWithObjects:person1,person2,person3,person4, nil];
    
    //赛选满足谓词的条件返回是数组 满足年龄大于15
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"age>=%d",15]]);
    //满足姓名
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name=%@",@"张三"]]);
    //或预算符
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name=%@ or age=%d",@"张三",15]]);
    //in运算符
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.name in {'张三','李四','赵六'}"]]);
    //某个字符开头
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.name beginswith '张'"]]);
    //某个字符结尾
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.name endswith '三'"]]);
    //包含字符
    NSLog(@"%@",[storage filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.name contains '三'"]]);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值