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...
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With