使用NSPredicate过滤数组

时间:2014-12-01 00:04:07

标签: objective-c arrays xcode filter nspredicate

我想要的是我的赃物,苹果,橘子的数组,如果它包含一个字母或一串字母,就会被它包含的内容过滤掉。到目前为止我有这个:

NSArray* test = @[@"swag", @"Apples", @"Oranges"];
//NSString *nameOnly = [[onlyApps lastPathComponent] stringByDeletingPathExtension]
NSString *searchinput = @"a";
NSPredicate * fltrSearch = [NSPredicate predicateWithFormat:@"%@ contains[cd] '%@'", test,     searchinput];
NSArray * Search = [test filteredArrayUsingPredicate:fltrSearch];
NSLog(@"%@", fltrSearch);
NSLog(@"%@", Search);

1 个答案:

答案 0 :(得分:0)

请参阅以下修改后的代码: -

NSArray* test = @[@"swag", @"Apples", @"Oranges"];
NSString *searchinput = @"a";
NSPredicate * fltrSearch = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",searchinput];
NSArray * Search = [test filteredArrayUsingPredicate:fltrSearch];
NSLog(@"%@", Search);

您的predicateWithFormat行错了。所以只需替换以下行: -

NSPredicate * fltrSearch = [NSPredicate predicateWithFormat:@"%@ contains[cd] '%@'", test,     searchinput];

使用修改后的行: -

NSPredicate * fltrSearch = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",searchinput];

输出: -

(
    swag,
    Apples,
    Oranges
)