Vahid Hashemi
Vahid Hashemi

Reputation: 5240

from a NSDictionary I only get 0 or null what should I do?

this is my snippet

NSArray * alphabets = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",nil];
NSMutableDictionary * alphaToNum = [NSMutableDictionary dictionary];

NSInteger index =0;

for (NSString * character in alphabets) {

    index++;
    [alphaToNum setObject:character forKey:[NSNumber numberWithInteger:index]];
}

NSLog(@"%@",[alphaToNum objectForKey:@"d"]);

and every time I try to get some value for my key I only get 0 .

Upvotes: 0

Views: 132

Answers (3)

itsaboutcode
itsaboutcode

Reputation: 25109

Following code will produce your desired result.

NSLog(@"%@",[alphaToNum objectForKey:[NSNumber numberWithInteger:4]]);

Problem with your NSlog is this.

Keys are made up of NSNumbers, which are starting from 1, not of alphabets. => since there is no key with letter 'd', it will send you null in return.

Upvotes: 0

jrturton
jrturton

Reputation: 119292

Your keys are NSNumbers, your objects are the letters from a to z. There is no object for key @"d". There will be an object, the string @"d", for the key [NSNumber numberWithInt:4]. Have you got your keys and objects the wrong way around? What do you actually want to do?

Upvotes: 0

Simon Lee
Simon Lee

Reputation: 22334

You need...

NSLog(@"%@",[alphaToNum objectForKey:[NSNumber numberWithInteger:[alphabets indexOfObject:@"d"]]]);

Upvotes: 2

Related Questions