user4951
user4951

Reputation: 33050

How to filter these NSArray with NSPredicate?

-(void) vUpdateHistoryAndSuggestionEntries
{
    NSArray * potentialHistory = [[self class] arHistory];
}

potentialHistory is an array of NSString objects.

I want to filter only elements that start with, for example, @"Cat" in case insensitive manner.For example,

if the NSArray contains

Cathy Cat Dog

Then I want an array that contains

Cathy Cat

I think NSPredicate is ideal for this. Any other ways will be fine too.

There are similar questions. However, in those questions, NSArray contains dictionary. I want to filter based on the actual element of the array instead of element of element of the array.

Upvotes: 0

Views: 183

Answers (4)

Durga Vundavalli
Durga Vundavalli

Reputation: 1828

NSString *filterStr = [NSString stringWithFormat:@"name LIKE[c] '*%1$@*'",searchStr];
NSPredicate *predicate = [NSPredicate predicateWithFormat:filterStr];
NSMutableArray *tempArray = [yourArrayofNames filteredArrayUsingPredicate:predicate];

//here name is your property and yourArrayofNames is your array of objects.

Upvotes: 0

Schrodingrrr
Schrodingrrr

Reputation: 4271

You do not need NSPredicate for simply this.

for (NSString* item in arHistory){

    if ([item rangeOfString:@"cat" options:NSCaseInsensitiveSearch].location == 0){//occurs at beginning

        [potentialHistory addObject:item];
    }
}

EDIT: If potentialHistory is immutable, use another array to store these and init potentialHistory with it.

NSArray* potentialArray = [NSArray arrayWithArray:(NSArray*)array]

Upvotes: -1

mmackh
mmackh

Reputation: 3630

Here's an example of how to use NSPredicate:

NSArray *sampleArray = @[@"Cathy", @"Cat", @"Dog"];
NSArray *filteredSampleArray = [sampleArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self contains[c] %@",@"ca"]];
NSLog(@"%@",filteredSampleArray);

This will output:

( Cathy, Cat )

Upvotes: 0

Prashant Nikam
Prashant Nikam

Reputation: 2251

NSArray *yourArray;
NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'C'"];
NSArray *theFilteredArray = [yourArray filteredArrayUsingPredicate:aPredicate];

Hope this will help you.

Upvotes: 2

Related Questions