NSPredicate的在查詢中的簡單使用,nspredicate查詢
上代碼吧,每塊代碼都可以直接跑,並附有注釋和運行結果
//直接使用 == 嚴格匹配NSArray *arrOriginal = [NSArray arrayWithObjects:@"c1",@"c", @"cd", @"cdd", @"cd", nil];NSString *match = @"cd";NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", match];NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];NSLog(@"result===%@",results);
列印結果:
result===(
cd,
cd
)
//like匹配,類似Sql中的用法NSArray *arrOriginal = [NSArray arrayWithObjects:@"c1",@"d", @"cd", @"cdd", @"dd",@"dcd",@"cdc", nil];NSString *match = @"c*";//以c開頭NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match];NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];NSLog(@"result===%@",results);
列印結果:
result===(
c1,
cd,
cdd,
cdc
)
//忽略大小寫進行匹配NSArray *arrOriginal = [NSArray arrayWithObjects:@"Cdd",@"cDc",@"cdd",@"dcdd", nil];NSString *match = @"cd*";NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[c] %@", match];NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];NSLog(@"result===%@",results);
列印結果:
result===(
Cdd,
cDc,
cdd
)
//利用正則表達是進行過濾NSArray *arrOriginal = [NSArray arrayWithObjects:@"c1",@"C3",@"d2",@"c2", nil];NSString *match = @"^c\\d?";NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];NSLog(@"result===%@",results);
列印結果:
result===(
c1,
c2
)
//利用過濾器(數組)進行過濾NSArray *arrFilter = [NSArray arrayWithObjects:@"aa", @"bb", nil];NSArray *arrOriginal = [NSArray arrayWithObjects:@"dds",@"bb",@"c1",@"C3",@"bb",@"aa",@"c2", nil];NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", arrFilter];//不包含符合過濾器的內容NSArray *results = [arrOriginal filteredArrayUsingPredicate:predicate];NSLog(@"result===%@",results);
列印結果:
result===(
dds,
c1,
C3,
c2
)