NSPredicate谓词

//predicate谓词:常用的是过滤数组中的元素

//最常用的三种

//1.@"SELF CONTAINS 'aa'"包含某个字符串

//2.@"SELF BEGINSWITH 'aa'"以某个字符串开头

//3.@"SELF ENDSWITH 'ng'"以某个字符串结尾

NSArray *array = @[@"fuzhou", @"xiamen", @"longyan", @"quanzhou", @"putian", @"jinjiang", @"sanming", @"zhanzhou", @"xianyou", @"siming", @"huli"];

//创建谓词的NSPredicate对象查找某些符合要求的字符串

NSPredicate *containPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS 'an'"];

NSArray *containArray = [array filteredArrayUsingPredicate:containPredicate];

NSPredicate *beginPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH 'fu'"];

NSArray *beginArray = [array filteredArrayUsingPredicate:beginPredicate];

NSPredicate *endPredicate = [NSPredicate predicateWithFormat:@"SELF ENDSWITH 'ng'"];

NSArray *endArray = [array filteredArrayUsingPredicate:endPredicate];

//LIKE模糊查询

//*代表任意位置

//?代表一位

//??li---->*li

NSPredicate *likePredicate = [NSPredicate predicateWithFormat:@"SELF LIKE '??li'"];

NSArray *likeArray = [array filteredArrayUsingPredicate:likePredicate];

//查找某个元素字符串

NSString *str1 = @"xiamen";

//==固定两个'=='

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@",str1];

NSArray *ary = [array filteredArrayUsingPredicate:predicate];

//查询一个数组中是否包含另一个数组中的元素(两个数组中是否有相同的内容)

NSArray *array2 = @[@"xiamen", @"nanjing", @"zhengzhou"];

//SELF IN %@去重

NSPredicate *betweenPredicate = [NSPredicate predicateWithFormat:@"SELF IN %@",array2];

NSArray *betweenArray = [array filteredArrayUsingPredicate:betweenPredicate];

//利用谓词判断比较数值的大小

NSPredicate *numPredicate = [NSPredicate predicateWithFormat:@"self >= 10"];

BOOL isBig = [numPredicate evaluateWithObject:@8];

NSLog(@"%@",isBig ?@"大":@"小");


//前后缀筛选

BOOL has1 = [str1 hasPrefix:@"ba"]

BOOL has2 = [str1 hasSuffix:@"def"];

//谓词的表达式

NSString *str =@"self beginswith [c] 'a'";

//开头beginswith [c]不区分大小写

//容量contains是否包含

//结尾endswith

//开始匹配

BOOL isOk = [predicate evaluateWithObject:@"Amy"];

//固定位?:一位模糊位*

@"self like '???b*'"

//判断邮箱

@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{1,5}"

//根据谓词过滤数组

arr = [arr filteredArrayUsingPredicate:pre];

//过滤数组相交部分

NSPredicate *pre = [NSPredicate predicateWithFormat:@"self in %@",arr1];

//条件筛选

@"self.age < 14"

你可能感兴趣的:(NSPredicate谓词)