Dr.Kameleon
Dr.Kameleon

Reputation: 22810

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...

Upvotes: 5

Views: 5764

Answers (3)

Parag Bafna
Parag Bafna

Reputation: 22930

You can also use indexOfObjectPassingTest: method of NSArray class. Available in Mac OS X v10.6 and later.

@implementation NSArray (hasPrefix)

-(NSMutableArray *)filteredByPrefix:(NSString *)pref
{
    NSMutableArray* newArray = [[NSMutableArray alloc] initWithCapacity:0];

    NSUInteger index = [self indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
        if ([ obj hasPrefix:pref]) {
            [newArray addObject:obj];
            return YES;
        } else
            return NO;
    }];

    return [newArray autorelease];

}

@end

Upvotes: 1

yuji
yuji

Reputation: 16725

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.

Upvotes: 17

Ken Thomases
Ken Thomases

Reputation: 90531

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];

Upvotes: 1

Related Questions