Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering NSArray string elements

So, basically I have an NSArray.

I want to get an array with the contents of the initial array after having filtered those e.g. NOT beginning by a given prefix.

It think using filteredArrayUsingPredicate: is the best way; but I'm not sure on how I could do it...

This is my code so far (in a NSArray category actually) :

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

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

    return newArray;
}

Is it the most Cocoa-friendly approach? What I want is something as fast as possible...

like image 290
Dr.Kameleon Avatar asked Apr 04 '12 09:04

Dr.Kameleon


2 Answers

Here's a much simpler way using filteredArrayUsingPredicate::

NSArray *filteredArray = [anArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF like  %@", [pref stringByAppendingString:@"*"]];

This filters the array by checking that it matches the string made up of your prefix followed by a wildcard.

If you want to check the prefix case-insensitively, use like[c] instead.

like image 122
yuji Avatar answered Nov 15 '22 01:11

yuji


You can use -indexesOfObjectsPassingTest:. For example:

NSIndexSet* indexes = [anArray indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
    return [obj hasPrefix:pref];
}];
NSArray* newArray = [anArray objectsAtIndexes:indexes];
like image 23
Ken Thomases Avatar answered Nov 15 '22 03:11

Ken Thomases