Search code examples
objective-cplistuisearchbarpredicate

How to use predicate with nsdictionary?


I have a dictionary within another dictionary in my plist as below:

    <dict1>Root
         <dict2>A
             <dict3>Apple
                   <string>"About Apple..."
             <dict3>Arrow
                   <string>"About Arrow..."
         <dict2>B
             <dict3>Ball
                   <string>"About Ball..."
         <dict2>C

                     etc...

The user is currently using a search bar to search for a string. How can I look with the third level and compare each string using a predicate and return results and pass these to table view cells?

I tried following this video tutorial but I fail on the predicate.

https://www.youtube.com/watch?v=UE4h_Td6W6U

He has written his dictionary to an array from what I can see. Mine seems a little more complicated.

I am new to this so any help will be appreciated.


Solution

  • You need to traverse down your dictionary list until you get to the Dictionary that you're looking for. It looks something like this:

        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"YOURPLIST" ofType:@"plist"];
        NSMutableDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath]; //This puts you into the root directory
        NSMutableDictionary *secondLevel = [NSMutableDictionary dictionaryWithDictionary:[dictionary objectForKey:[NSString stringWithFormat:@"A"]]]; //or B or C etc
        NSMutableDictionary *thirdLevel = [NSMutableDictionary dictionaryWithDictionary:[dictionary objectForKey:[NSString stringWithFormat:@"Apple"]]]; 
    

    This will put you in the Apple dictionary, however to be able to fetch the string you need a key attached to it. Your dictionary should look like

        <key>Some key name</key>
        <string>About Apple...</string>
    

    And then you could fetch the string using the key through:

        NSString *string = [thirdLevel objectForKey:@"Some key name"];
    

    If you're strictly searching for strings, you could do something like this Search String in NSDictionary store in NSMutableArray