iOS.Lover
iOS.Lover

Reputation: 6051

Read specific key from NSDictionary

I am trying to read data from specific key in plist file ! but I have no idea why app crashes !!! here is my code :

 NSString *loadData = [[NSBundle mainBundle]pathForResource:@"Dinosaurs" ofType:@"plist"];
    NSDictionary *dinoDictionary = [[NSDictionary alloc]initWithContentsOfFile:loadData];
    NSDictionary *dinosaurs = (NSDictionary*)[[dinoDictionary allKeys]objectAtIndex:0];

//app crashes at this line 
    NSString *DINOIMAGE = (NSString*)[dinosaurs valueForKey:@"DINOIMAGE"];

    NSLog(@"%@ , %@",dinosaurs , DINOIMAGE);

crash log :

 Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7ff7faf0f790> valueForUndefinedKey:]: this class is not key value coding-compliant for the key DINOIMAGE.'
*** First throw call stack:

plist file : enter image description here

Upvotes: 0

Views: 60

Answers (2)

vadian
vadian

Reputation: 285079

You concealed that the requested dictionary is a sub-dictionary with key SCELIDOSAURUS

NSString *loadData = [[NSBundle mainBundle]pathForResource:@"Dinosaurs" ofType:@"plist"];
NSDictionary *dinoDictionary = [[NSDictionary alloc] initWithContentsOfFile: loadData];
NSDictionary *scelidosaurus = (NSDictionary *)dinoDictionary[@"SCELIDOSAURUS"]
NSString *DINOIMAGE = (NSString *)scelidosaurus[@"DINOIMAGE"];
NSLog(@"%@, %@", dinoDictionary, DINOIMAGE);

Upvotes: 1

paulvs
paulvs

Reputation: 12053

You're grabbing the first key in the dinoDictionary and using it as if it were a dictionary (it's a NSString) here:

NSDictionary *dinosaurs = (NSDictionary*)[[dinoDictionary allKeys]objectAtIndex:0];
//app crashes at this line 
NSString *DINOIMAGE = (NSString*)[dinosaurs valueForKey:@"DINOIMAGE"];

That's what the error message says: The NSString class cannot be queried for the key DINOIMAGE.

You should simply query the dinoDictionary with the key DINOIMAGE as follows:

NSString *loadData = [[NSBundle mainBundle]pathForResource:@"Dinosaurs" ofType:@"plist"];
NSDictionary *dinoDictionary = [[NSDictionary alloc] initWithContentsOfFile: loadData];
NSString *DINOIMAGE = (NSString *)dinoDictionary[@"DINOIMAGE"];
NSLog(@"%@, %@", dinoDictionary, DINOIMAGE);

Upvotes: 1

Related Questions