xcode 按字符串内容过滤 NSMutableArray 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9980625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
xcode filter NSMutableArray elements by string contents
提问by Jaume
I would like to filter NSMutableArray elements that contains "some" string. ListArchives is filled with string elements and listFiles must be a filtered one. XCode generates an alert at last posted line. What am doing wrong? any other method to filter elements of NSMutableArray?
我想过滤包含“一些”字符串的 NSMutableArray 元素。ListArchives 充满了字符串元素,而 listFiles 必须是经过过滤的元素。XCode 在最后发布的行生成警报。做错了什么?任何其他过滤 NSMutableArray 元素的方法?
NSString *match = @"*some*";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];
listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];
回答by dasblinkenlight
Try using contains
instead of like
, for example as follows:
尝试使用contains
代替like
,例如如下:
NSString *match = @"some";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", match];
listFiles = [[listArchives filteredArrayUsingPredicate:sPredicate] mutableCopy];
回答by Praveen-K
If you want to search as 'like' operator. Lets say you have a NSArray with following contents :
如果您想搜索为“喜欢”运算符。假设您有一个包含以下内容的 NSArray:
static int count = 0;
NSArray *results = [NSArray arrayWithObjects:@"What was", @"What is", @"What will", nil];
NSString *targetString = @"What"
for (NSString *strObj in results)
{
if ([strObj rangeOfString:targetString].location != NSNotFound){
NSLog (@"Found: %@", strObj);
count = count + 1;
}
}
NSLog(@"There were %d occurence of %@ string",count,targetString);
回答by umer sufyan
NSString *match = @"some";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", match];
listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];
For robust searching this can serve you as some what "Like" serve in SQL
.
对于强大的搜索,这可以为您提供一些“喜欢”服务SQL
。