乐于助人篇之谓词

本文介绍了NSPredicate的基础使用方法,包括创建过滤条件、判断对象是否满足条件及过滤出符合条件的对象等。此外,还提供了谓词语法示例,如模糊搜索、字符串正则匹配等。

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

我是好人!喜欢乐于助人 哇哈哈哈! 帮助别人的同时就是提升自己的过程。。

献上图一枚

######NSPredicate 用于指定过滤条件,主要用于从集合中分拣出符合条件的对象,也可以用于字符串的正则匹配。

1.创建NSPredicate(相当于创建一个过滤条件)

  NSPredicate *predicate =         [NSPredicate predicateWithFormat:@"过滤条件"];
复制代码

2.判断指定的对象是否满足NSPredicate创建的过滤条件

  [predicate evaluateWithObject:person];
复制代码

3.过滤出符合条件的对象(返回所有符合条件的对象)

  NSArray *persons = [array filteredArrayUsingPredicate:predicate];
复制代码
  • 1.先创建一个person对象
  • @interface Person: NSObject{
  • NSString *name;
  • int age;
  • }
  • 2.创建一个数组,在数组种加入多个person对象
  • NSArray *array=[NSArray arrayWithObjects:person1,person2,person3,person4,...,nil];
  • 3.使用NSPredicate来过滤array种的person

找出array种age小于20的person

   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age < 20"];
  for(Person *person in array){
if([predicate evaluateWithObject:person]){ //判断指定的对象是否满足
}
   }

   NSArray *persons = [array filteredArrayUsingPredicate:predicate];//获取所有age小于20的person
复制代码

#####谓词的一些语法

  • like 模糊搜索 、like
    j 包含j的 j 以j结尾的 j 以j开头的 #####匹配正则表达式 NSPredicate 使用MATCHES 匹配正则表达式,正则表达式的写法采用international components   for Unicode (ICU)的正则语法。   例:   NSString *regex = @"^A.+e$";//以A 开头,以e 结尾的字符。   NSPredicate *pre= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];   if([pre evaluateWithObject: @"Apple"]){   printf("YES\n");   }else{   printf("NO\n");   }

// 包含 NSPredicate *pre = [NSPredicate predicateWithFormat:@"name  CONTAINS '%@'",@""];

// 开头
复制代码

NSPredicate *pre = [NSPredicate predicateWithFormat:@"name  BEGINSWITH '%@'",@""];

//结尾的
复制代码

NSPredicate *pre = [NSPredicate predicateWithFormat:@"name  ENDSWITH '%@'",@""];

以上说的都是对象种的属性匹配,如果数组种都是字符串如何匹配--self

NSMutableArray *array=[NSMutableArray arrayWithObjects: @"abc", @"def", @"ghi",@"jkl",  nil];     NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF=='abc'"];

[array filterUsingPredicate:pre];     NSArray *array2 = [array filteredArrayUsingPredicate:pre];

用谓词过滤数组的时候可变数组 可以在原来的数组中操作,也可以返回一个新的数组

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值