c/c++開發人員一定很喜歡用boost庫,它有很強大的容器功能,在iOS開發中Array也相當於容器,功能也比較強大。NSArray可以用NSPredicate來過濾數組內容,NSPredicate有點像sql+正則表達,具體文法在此不談,自己google一堆。
不想打字了(我超級懶),用代碼說話:
view plaincopy to clipboardprint?
- //找出一個數組
- NSFileManager *fileManager = [NSFileManager defaultManager];
- NSString *defaultPath = [[NSBundle mainBundle] resourcePath];
- NSError *error;
-
- NSArray *directoryContents = [fileManager contentsOfDirectoryAtPath:defaultPath error:&error]
- //匹配字串,反回結果, SELF==表示數組中每一個元素
- NSString *match = @"imagexyz-999.png";
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", match];
- NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
-
- //近似匹配字串,類似SQL中的文法
- NSString *match = @"imagexyz*.png";
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like %@", match];
- NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
- //不區分大小寫匹配
- NSString *match = @"imagexyz*.png";
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];
- NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];
- //正則匹配
- NSString *match = @"imagexyz-//d{3}//.png";
- NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
- NSArray *results = [directoryContents filteredArrayUsingPredicate:predicate];