4

I have an

Array
  Item 0 -- Dictionary
    Sport -- String
    Mens  -- Array
      Item 0 -- Dictionary
        Name -- String
        Rules -- String
        Description -- String
    Womens  -- Array
      Item 0 -- Dictionary
        Name -- String
        Rules -- String
        Description -- String
   Item 1 -- Dictionary
      And so on.....

I would like to create a NSPredicate searching if a given string is contained inside of Name. How can I achieve reaching that deep?

If you cant understand the graph. I have an array full of dictionaries, Inside the dictionaries are A string, An Array of dictionaries, and An Array of dictionaries, Inside of the dictionaries are string objects

So How do I get into the second dictionaries and search the Name key

Thanks in advance

anotherDeveloper
  • 77
  • 1
  • 1
  • 8

2 Answers2

22

You need the following

NSString *str = <search string>;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"ANY Mens.Name LIKE %@ OR ANY Womens.Name LIKE %@", str, str];
NSArray *result = [your_array filteredArrayUsingPredicate:pred];
BOOL success = result.count > 0;
malex
  • 9,874
  • 3
  • 56
  • 77
  • 3
    I do not understand why "LIKE" is so often suggested in a predicate. "LIKE" does a simple wildcard search, so `"name LIKE 'A*B'"` finds all names starting with an A and ending with a B. In most cases, you want "==" or perhaps "BEGINSWITH" or "CONTAINS". - (+1) though. – Martin R Jan 18 '14 at 08:31
  • You should use exactly what is more appropriate in your own search task. Here LIKE is only for illustration. – malex Jan 18 '14 at 08:34
  • The question is not in the choice between like, contains or something else. Beginners in using predicates usually don't realize how to make deep search with different key words as ANY. – malex Jan 18 '14 at 09:50
  • ...for pointing out the 'ANY'. Without that and using the LIKE would cause an error with this data layout. Thanks – StuartM Jan 27 '15 at 15:47
  • { error: 0, error_msg: "No error", feed: [ { company_id: 127, company_news: [ { company_name: "test company", short_description: "This is just Test", }, { company_name: "test company", short_description: "This is just Test", } ] } how search this type array and dict – Patel Maulik Feb 20 '16 at 09:28
-7

To get to the name you have to do this:

for (NSDictionary *itemDict in myArray)
{
    NSArray *womensArray = (NSArray*)[itemDict objectForKey:@"Womens"];

    for (NSDictionary *womenItemDict in womensArray)
    {
          NSString *name = [womenItemDict objectForKey:@"Name"];

          //Do the comparison here
    }
}
Rohan Bhale
  • 1,323
  • 1
  • 11
  • 29