谓词的使用 -ios

时间:2023-03-09 02:57:34
谓词的使用 -ios
#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCopying>
@property(nonatomic,copy) NSString *name;
@property(nonatomic,retain) NSNumber *age;
-(void) setNewName:(NSString *) name;
@end
#import "Person.h"

@implementation Person:NSObject

- (id)copyWithZone:(NSZone *)zone{
Person *person=[[[self class] allocWithZone:zone] init];
person.name=_name;
person.age=_age;
return person;
}
-(void) setNewName:(NSString *) name{
self.name=name;
}
-(NSString *)description{
NSString *description=[NSString stringWithFormat:@"年龄:%@;名字:%@",_age,_name];
return description;
}
@end
//谓词用法 NSPredicate
NSMutableArray *array=[NSMutableArray array];
for (int i=0; i<10; i++) {
Person *person=[[Person alloc]init];
[person setAge:@(20+i)];
person.name=[NSString stringWithFormat:@"jage-%d",i];
[array addObject:person];
}
//大,小,等;等运算过滤
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age<%d",25];
NSPredicate *predicate2=[NSPredicate predicateWithFormat:@"age<23",23];
NSPredicate *predicate3=[NSPredicate predicateWithFormat:@"age<27 and age>25"];
NSPredicate *predicate4=[NSPredicate predicateWithFormat:@"age<27 && age>25"];
NSPredicate *predicate5=[NSPredicate predicateWithFormat:@"age<23 || age>26"];
NSPredicate *predicate6=[NSPredicate predicateWithFormat:@"name='jage-3'"];
//在某个里面
NSPredicate *predicate7=[NSPredicate predicateWithFormat:@"name in {'jage-1','jage-5'}"];
NSArray *inArray=@[@"jage-1",@"jage-4",@"jage-3"];
NSPredicate *predicate8=[NSPredicate predicateWithFormat:@"name in %@",inArray];
//已什么开头,注意加单引号
NSPredicate *predicate9=[NSPredicate predicateWithFormat:@"name BEGINSWITH 'jage'"];
//已什么结尾,注意加单引号
NSPredicate *predicate10=[NSPredicate predicateWithFormat:@"name ENDSWITH '-9'"];
//包含,注意加单引号
NSPredicate *predicate11=[NSPredicate predicateWithFormat:@"name CONTAINS '-3'"];
//like,注意加单引号
NSPredicate *predicate12=[NSPredicate predicateWithFormat:@"name LIKE 'jage-?'"];
NSPredicate *predicate13=[NSPredicate predicateWithFormat:@"name LIKE '*-2'"]; for (Person *person in array) {
if([predicate6 evaluateWithObject:person]){//逐个对象判断
NSLog(@"%@",person);
}
}
//对数组过滤
NSArray *filterArray=[array filteredArrayUsingPredicate:predicate13];
NSLog(@"%@",filterArray);