xcode按字符串内容过滤NSMutableArray元素

时间:2012-04-02 17:03:29

标签: iphone objective-c ios xcode cocoa-touch

我想过滤包含“some”字符串的NSMutableArray元素。 ListArchives填充了字符串元素,listFiles必须是过滤后的元素。 XCode在最后发布的行生成警报。怎么了?过滤NSMutableArray元素的任何其他方法?

NSString *match = @"*some*"; 
listFiles = [[NSMutableArray alloc] init];

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF like[cd] %@", match];

listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];

3 个答案:

答案 0 :(得分:4)

尝试使用contains代替like,例如:

NSString *match = @"some"; 
listFiles = [[NSMutableArray alloc] init];

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", match];

listFiles = [[listArchives filteredArrayUsingPredicate:sPredicate] mutableCopy];

答案 1 :(得分:2)

如果你想搜索'喜欢'运营商。 假设您有一个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);

答案 2 :(得分:0)

NSString *match = @"some";
listFiles = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", match];
listFiles = [listArchives filteredArrayUsingPredicate:sPredicate];

对于强大的搜索,这可以为您提供SQL中的“赞”服务。