首页 > 代码库 > iOS NSPredicate
iOS NSPredicate
NSPredicate和数据库的SQL语句具有相似性,都是从数据堆中根据条件进行筛选,被广大开发者忽略的NSPredicate到底有什么功能,直接上代码。
一、筛选array1在array2中的元素
-(void)selectElement
{
NSArray *array1 = [NSArray arrayWithObjects:@1,@2,@3,@5,@5,@6,@7, nil];
NSArray *array2 = [NSArray arrayWithObjects:@4,@5, nil];
//SELF 指向filteredArrayUsingPredicate的调用者
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF in %@",array2];
NSArray *temp1=[array1 filteredArrayUsingPredicate:predicate];
NSLog(@"%@",temp1);
}
二、比较运算
-(void)predicateCompare
{
NSArray *array = [NSArray arrayWithObjects:@1,@2,@3,@5,@5,@6,@7, nil];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF > 4"];
NSArray *tempAry=[array filteredArrayUsingPredicate:predicate];
[tempAry enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"tempary=%@",obj);
}];
}
三、范围运算
-(void)predicateBetween
{
NSArray *array = [NSArray arrayWithObjects:@1,@2,@3,@5,@5,@6,@7, nil];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF BETWEEN {2,5}"];
NSArray *tempAry= [array filteredArrayUsingPredicate:predicate];
[tempAry enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",tempAry);
}];
}
四、字符串本身:SELF
-(void)selfCompare
{
NSArray *array = [NSArray arrayWithObjects:@"beijing",@"shanghai",@"hangzhou",@"shenzhen",@"guangzhou", nil];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"SELF == ‘beijing‘"];
NSArray *tempAry= [array filteredArrayUsingPredicate:predicate];
[tempAry enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",tempAry);
}];
}
五、字符串相关
-(void)characterAbout
{
/*
例:@"name CONTAINS[cd] ‘ang‘" //包含某个字符串
@"name BEGINSWITH[c] ‘sh‘" //以某个字符串开头
@"name ENDSWITH[d] ‘ang‘" //以某个字符串结束
c代表不区分大小写,d代表不区分重音
*/
NSArray *array = [NSArray arrayWithObjects:@"beijing",@"Shanghai",@"hangzhou",@"shenzheN",@"taishan", nil];
//SELF CONTAINS[cd]‘ang‘
//SELF BEGINSWITH[c]‘s‘
NSString *str=@"SELF ENDSWITH[c]‘n‘";
NSPredicate *predicate=[NSPredicate predicateWithFormat:str];
NSArray *tempAry= [array filteredArrayUsingPredicate:predicate];
[tempAry enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",tempAry);
}];
}
六、通配符LIKE
-(void)like
{
/*
例:@"name LIKE[cd] ‘*er*‘" *代表通配符,Like也接受[cd].
@"name LIKE[cd] ‘???er*‘"
*/
NSArray *array1 = [NSArray arrayWithObjects:@"beijing",@"Shanghai",@"hangzhou",@"shenzheN",@"taishan", nil];
//SELF LIKE[cd]‘*ai*‘
NSString *str=@"SELF LIKE[cd]‘?ai*‘";
NSPredicate *predicate=[NSPredicate predicateWithFormat:str];
NSArray *tempAry= [array1 filteredArrayUsingPredicate:predicate];
[tempAry enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"--%@",tempAry);
}];
}
iOS NSPredicate