View Full Version : value for key does not return value expected

Jun 24, 2010, 01:35 PM
Hello. I am working on an application which contains a function that does some modulo operations on some unsigned long values. Specifically

-(NSDictionary*)rmdecode:(unsigned long)field{
NSMutableDictionary* returnDict=[NSMutableDictionary dictionaryWithCapacity:3];
unsigned long rm,reg,mod;


NSLog(@"mod:0x%x ",mod);
[returnDict setObject:[[NSNumber alloc]initWithShort:mod] forKey:@"mod"];
[returnDict setObject:[[NSNumber alloc]initWithShort:reg]forKey:@"reg"];
[returnDict setObject:[[NSNumber alloc]initWithShort:rm] forKey:@"rm"];

return returnDict;

However, when I return from this function and try to store the values they are not the same values that are stored when the function returns.
For example:

returnDict=[self rmdecode:d];
NSLog(@"dict[mod]:0x%x",[[returnDict valueForKey:@"mod"]shortValue]);
m=[[returnDict valueForKey:@"mod"]shortValue];
r=[[returnDict valueForKey:@"reg"]shortValue];
rm=[[returnDict valueForKey:@"rm"]shortValue];
NSLog(@"m:0x%x r:0x%x rm:0x%x",d,IP);

Will generate output in the form:

2010-06-24 14:31:49.175 vm[10723:207] mod:0x3
2010-06-24 14:31:49.175 vm[10723:207] dict[mod]:0x3
2010-06-24 14:31:49.176 vm[10723:207] m:0xed r:0x8048172 rm:0x8048171

I am looking for the original values of mod,reg,and rm to be what is actually stored in m,reg,and rm. (In this case 0x3 for mod).
If anyone could shed some light on this I would greatly appreciate it.

Jun 24, 2010, 08:15 PM
NSLog(@"m:0x%x r:0x%x rm:0x%x",d,IP);

Take a second look at that line...

BTW you're leaking your NSNumber objects. Either create them with numberWithShort: or add an autorelease call.

Jun 24, 2010, 08:23 PM
yeah...i actually just noticed this about 10 minutes ago...that's embarrassing.

Are you saying:

[returnDict setObject:[[NSNumber alloc]initWithShort:mod]

would become:

[[returnDict setObject:[[NSNumber alloc]initWithShort:mod]autorelease]

Jun 24, 2010, 08:25 PM
Yes, but it's shorter to write:

[returnDict setObject:[NSNumber numberWithShort:mod]...

EDIT: also you should not use valueForKey: unless you have a good reason to. Use objectForKey: