过滤NSArray字符串元素

Dr.*_*eon 5 cocoa objective-c nsarray

所以,基本上我有一个NSArray.

我希望在过滤那些例如NOT以给定前缀开头的NOT之后得到一个包含初始数组内容的数组.

它认为使用filteredArrayUsingPredicate:是最好的方法; 但我不知道我怎么能这样做......

到目前为止这是我的代码(NSArray实际上是一个类别):

- (NSArray*)filteredByPrefix:(NSString *)pref
{
    NSMutableArray* newArray = [[NSMutableArray alloc] initWithObjects: nil];

    for (NSString* s in self)
    {
        if ([s hasPrefix:pref]) [newArray addObject:s];
    }

    return newArray;
}
Run Code Online (Sandbox Code Playgroud)

它是对Cocoa最友好的方法吗?我想要的是尽可能快的东西......

yuj*_*uji 16

这是一个更简单的方法filteredArrayUsingPredicate::

NSArray *filteredArray = [anArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF like  %@", [pref stringByAppendingString:@"*"]];
Run Code Online (Sandbox Code Playgroud)

这会通过检查数组是否匹配由前缀后跟通配符组成的字符串来过滤数组.

如果要不区分大小写检查前缀,请like[c]改用.

  • 谢谢,我用它来比较单词中任何位置的字符串: `[NSPredicate predicateWithFormat:@"SELF like[c] %@", [NSString stringWithFormat:@"*%@*",keyword]]` (2认同)