jaytrixz
jaytrixz

Reputation: 4079

How to Filter NSDictionary to DIsplay Certain Keyword in Objective-C

I want to actually check the contents inside of the dictionary if it has the keyword that I need and display it. If it doesn't have the keyword I'm looking for, it doesn't display it.

For example, a dictionary of cities and in each city, it has a description of that city. I want to look for a keyword "mall" in that description and if that city has that keyword, it should display the city and its description.

How can I do this? Thanks in advance! :)

Upvotes: 0

Views: 750

Answers (2)

TheNavigat
TheNavigat

Reputation: 865

valueForKey method.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDictionary/valueForKey:

You can just make an if situation, if it returns nil, display nothing. Otherwise, display the returned value.

Here's an example of using it

NSString *string = [NSString stringWithString:[dictionary valueForKey:@"mall"]]; if (string) //Send that string to somewhere where it would be visible ;

Upvotes: 0

rdelmar
rdelmar

Reputation: 104082

I would loop through the dictionary, and use rangeOfString to look for the word "mall"

    NSMutableArray *array = [NSMutableArray array];
    for (NSString *aKey in [dict allKeys]) {
        NSString *desc = [dict valueForKey:aKey];
        if ([desc rangeOfString:@"mall"].length == 4) {
            [array addObject:[NSDictionary dictionaryWithObject:desc forKey:aKey]];
        }
    }
    //do what you want with array to display the values

Upvotes: 1

Related Questions