NSPredicate的用法、数组去重、比较...
一般來說這種情況還是蠻多的,比如你從文件中讀入了一個array1,然后想把程序中的一個array2中符合array1中內容的元素過濾出來。
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時字符串比較操作符,不是集合操作符。
NSPredicate的用法 ?http://www.cnblogs.com/MarsGG/articles/1949239.html
轉載于:https://www.cnblogs.com/yema/p/5052801.html
總結
以上是生活随笔為你收集整理的NSPredicate的用法、数组去重、比较...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: scroll-view 横向滑动无效的问
- 下一篇: matlab如何将二进制文件写入txt文