开发者

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"] );
}


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"...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜