How can get the values of NSDictionary using keys where the dictionaries are stored in NSArray?

I have created 5 NSDictionary's. I stored them in NSArray. I need to get the values stored in NSDictionaries. How can do it ? I tried calling [[array objectAtIndex:i]objectForKey:key1]. But, it is crashing by giving the message:unrecognized selector sent to instance How to get the data ?

NSDictionary *enemy1, *enemy2;
NSArray *enemyData;
-(void)viewDidLoad
{
enemy1 = [NSDictionary dictionaryWithObjectsAndKeys:@"3", @"Countdown speed", @"3", @"Enemy gun draw", @"1", @"Enemy gun fire", @"0.8", @"Enemy hit probability", @"1", @"Enemy re-fire interval", nil];
enemy2 = [NSDictionary dictionaryWithObjectsAndKeys:@"3", @"Countdown speed", @"2.8", @"Enemy gun draw", @"0.9", @"Enemy gun fire", @"0.8", @"Enemy hit probability", @"0.9", @"Enemy re-fire interval", nil];    
enemyData = [NSArray arrayWithObjects:@"enemy1", @"enemy2", nil];
NSLog(@"Value in Array: %f", [ [enemyData objectAtIndex:1]objectForKey:@"Enemy gun draw"] );
}

Answers


You are adding the strings @"enemy1" and @"enemy2" to your array, not the dictionaries.

Correct the line as follows: nemyData = [NSArray arrayWithObjects:enemy1, enemy2, nil]; and you should be good.

Note that you might run into a memory problem because your variables are autoreleased, if you want to access them later (which i suppose) you need to retain them.


Apart from the issue you raised (which has already been answered), there is also a problem with the NSLog format string. %f is for doubles, not objects. You need to use %@ to format anything returned by NSDictionary's objectForKey: method. Incidentally, the objects you are storing are NSStrings. NSNumbers might be better e.g.

enemy1 = [NSDictionary dictionaryWithObjectsAndKeys:
                          [NSNumber numberWithInt: 3], @"Countdown speed",
                          [NSNumber numberWithDouble: 1.0], @"Enemy gun fire"...

Need Your Help

ASP.net Form Auth with MySQL

c# mysql asp.net

I am writing a website in asp.net with .net 4.0 and using MySQL 6.7.4.0,

Use Eclipse to Programmatically Track Execution Path

java eclipse plugins

I know that Eclipse has powerful debugging capabilities. Are there any hooks that allow plug-ins to keep track of the code path followed when an open project is run?