NSPredicate過濾數組元素的用法

原文鏈接:http://www.cnblogs.com/MarsGG/articles/1949239.html

一般來說這種情況還是蠻多的,比如你從文件中讀入了一個array1,然後想把程序中的一個array2中符合array1中內容的元素過濾出來。
正 常傻瓜一點就是兩個for循環,一個一個進行比較,這樣效率不高,而且代碼也不好看。
其實一個循環或者無需循環就可以搞定了,那就需要用搞 NSPredicate這個類了~膜拜此類~
1)例子一,一個循環
NSArray *arrayFilter = [NSArray arrayWithObjects:@"pict", @"blackrain", @"ip", nil];
NSArray *arrayContents = [NSArray arrayWithObjects:@"I am a picture.", @"I am a guy", @"I am gagaga", @"ipad", @"iphone", nil];
我想過濾arrayContents的話只要循環 arrayFilter就好了
int i = 0, count = [arrayFilter count];
for(i = 0; i < count; i ++)
{
    NSString *arrayItem = (NSString *)[arrayFilter objectAtIndex:i];
    NSPredicate *filterPredicate = [[NSPredicate predicateWithFormat:@"SELF CONTAINS %@", arrayItem];
    NSLog(@"Filtered array with filter %@, %@", arrayItem, [arrayContents filteredArrayUsingPredicate:filterPredicate]);
}
當然以上代碼中arrayContent最好用mutable 的,這樣就可以直接filter了,NSArray是不可修改的。
2)例子二,無需循環
NSArray *arrayFilter = [NSArray arrayWithObjects:@"abc1", @"abc2", nil];
NSArray *arrayContent = [NSArray arrayWithObjects:@"a1", @"abc1", @"abc4", @"abc2", nil];
NSPredicate *thePredicate = [NSPredicate predicateWithFormat:@"NOT (SELF in %@)", arrayFilter];
[arrayContent filterUsingPredicate:thePredicate];
這樣arrayContent過濾出來的就是不包含 arrayFilter中的所有item了。
3)生成文件路徑下文件集合列表
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *defaultPath = [[NSBundle mainBundle] resourcePath];
NSError *error;
NSArray *directoryContents = [fileManager contentsOfDirectoryAtPath:defaultPath error:&error]
4)match的用法
1. 簡單比較
    NSString *match = @"imagexyz-999.png";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", match];
    NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
2. match裏like的用法(類似Sql中的用法)
   NSString *match = @"imagexyz*.png";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match];
    NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
3. 大小寫比較
[c]表示忽略大小寫,[d]表示忽略重音,可以在一起使用,如下:
  NSString *match = @"imagexyz*.png"; //其中*爲通配符
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];
  NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];

4.使用正則 
   NSString *match = @"imagexyz-\\d{3}\\.png";  //imagexyz-123.png
   NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
   NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];

總結:
1) 當使用聚合類的操作符時是可以不需要循環的
2)當使用單個比較類的操作符時可以一個循環來搞定
PS,例子 一中嘗試使用[@"SELF CONTAINS %@", arrayFilter] 來過濾會掛調,因爲CONTAINS時字符串比較操作符,不是集合操作符。

發佈了295 篇原創文章 · 獲贊 8 · 訪問量 112萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章