views:

42

answers:

2

Hi Friends. I have a simple question. How can I search NSMutable Dictionary? For eg. I have a dictionary like this:

      A1: Apple
      B1: Banana
      C1:  Cat
      D1:  Dog
      A2: Aeroplane
      B2: Bottle
      A3: Android

Now i want to search all the content (values) whose key starting with letter "A", means I want to search "Apple, Aeroplane and Android". I know how to search array but not Dictionary. Please help me out.

+3  A: 
for (NSString* key in theDictionary) {
   if ([key hasPrefix:@"A"]) {
      // found such a key, do whatever you like e.g.
      [theNewDictionary setObject:[theDictionary objectForKey:key] forKey:key];
   }
}
KennyTM
@Kenny: Thanks a lot man Its working perfectly. Thanks once again. :-)
Harsh
+1  A: 

Well, I don't think there's a built-in method for this.

Try:

NSMutableArray *results = [[[NSMutableArray alloc] init] autorelease];

for (NSString *key in [dictionary allKeys]) {
    if ([[key substringToIndex:1] isEqualToString:@"A"]) {
        [results addObject:[dictionary objectForKey:key]];
    }
}

return [results copy];
Tim van Elsloo
@Tim: Hey Tim you are right. You should see the above answer given by Kenny. Its working great for me.. Thanks for your consideration.
Harsh