Search from NSArray using Predicate

2019-07-15 17:34发布

问题:

my current array looks like below. i create this array format for sectionIndex table. so i can search from array and display search text using index table.

arrContent = (
    {
    key = A;
    value =         (
        Ac,
        Acting
    );
},
    {
    key = B;
    value =         (
        Basketball,
        Baseball
    );
},
    {
    key = C;
    value =         (
        Cat
    );
}
    {
    key = P;
    value =         (
        Panda,
        Peacock
    );
}
)

My Search code looks like below. and it is working fine.

-(void)searchText:(NSString *) text
{
[arrSearch removeAllObjects];
for (int i = 0; i < [arrContent count]; i++)
{
    NSMutableArray *temp = [[NSMutableArray alloc]init];
    NSMutableArray *arrFind = arrContent[i][@"value"];
    for (int j = 0; j < [arrFind count]; j++)
    {
        NSString *str = arrFind[j];
        // containsString: method find my string if its available within range
        if ([str containsString:text])
            [temp addObject:str];
    }

    if ([temp count])
    {
        [arrSearch addObject:@{@"key":arrContent[i][@"key"],@"value":temp}];
    }
}
NSLog(@"Search : %@",text);
NSLog(@"arrSearch : %@",arrSearch);
}

i got output like below. which is correct.

Search : ac
arrSearch : (
    {
    key = A;
    value =         (
        Ac,
        Acting
    );
},
    {
    key = P;
    value =         (
        Peacock
    );
}
)

I just want to ask that if is there any better way to search and get same output using NSPredicate because for loop will take time when lots of data.

Help would be appriciated.

回答1:

You could use the built in function on NSArray like this...

- (NSArray *)filterArrayUsingText:(NSString *)text
{
    NSMutableArray *filteredWordArray = [NSMutableArray array];

    for (NSDictionary *dictionary in yourWordArray) {
        NSArray *filteredWords = [self filterWordsFromArray:dictionary[@"value"] usingText:text];

        if (filteredWords) {
            [filteredWordArray addObject:@{@"key":dictionary[@"key"], @"value", filteredWords}];
        }
    }

    return filteredWordArray;
}

- (NSArray *)filterWordsFromArray:(NSArray *)wordArray usingText:(NSString *)text
{
    NSPredicate *predicate = [NSPredicate predicateWithBlock:^(NSString *theWord, NSDictionary *bindings) {
        return [theWord containsString:text];
    }];

    NSArray *filteredArray = [wordArray filteredArrayUsingPredicate:predicate];

    return filteredArray.count == 0 ? nil : filteredArray;
}

Also, make sure to use modern Obj-C syntax.

Also, the way the data is stored is a bit broken. For key/value pairs you don't store Key and Value.

You would store like this...

{
    A: (Ac,
        Acting),
    B: (Basketball,
        Baseball),
    C: (Cat),
    P: (Panda,
        Peacock)
}