Sunday, December 16, 2012

How to find a KEY from NSDictionary?

Here we will take NSMutableArray with objects and NSDictionary with Objects and Keys.



    NSMutableArray* mArray = [[NSMutableArray alloc]
                              initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F", nil];
    
    NSMutableDictionary *mDic = [NSMutableDictionary
                                 dictionaryWithObjectsAndKeys:@"F",@"mF",@"G",@"mG",@"B",@"mB",@"I",@"mI",nil];



We will write a Function which can provide us the array of founded keys after comparison.


-(NSMutableArray*)compareMyObject:(NSMutableArray*)array:(NSDictionary*)dic
{
    NSMutableArray* keysArray = [[NSMutableArray alloc] init];
for(int k=0;k<[array count];k++)
{
NSString* mStr = [array objectAtIndex:k];
        NSArray* array = [dic allKeysForObject:mStr];
if([array count])
        {
            [keysArray addObject:[array objectAtIndex:0]];
        }
}
    return keysArray;
}

Now we will call this method in the following format.

    NSMutableArray* keysArray =  [self compareMyObject:mArray:mDic];

The above method gives us the result array now, We will print and check those results.

    NSLog(@"total %d keys found. Those are %@",[keysArray count],[keysArray description]);


The result is : 

keysArray = (
    mB,
    mF