value for key does not return value expected

Discussion in 'iPhone/iPad Programming' started by l0uismustdie, Jun 24, 2010.

  1. macrumors regular

    Joined:
    Nov 30, 2009
    Location:
    Edinburgh, UK
    #1
    Hello. I am working on an application which contains a function that does some modulo operations on some unsigned long values. Specifically
    Code:
    -(NSDictionary*)rmdecode:(unsigned long)field{
    	NSMutableDictionary*		returnDict=[NSMutableDictionary dictionaryWithCapacity:3];
    	unsigned long						rm,reg,mod;
    	
    	rm=field%8;
    	field=field/8;
    	reg=field%8;
    	field=field/8;
    	mod=field%8;
    
    	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:
    Code:
    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:
    Code:
    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.
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    Code:
    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.
     
  3. thread starter macrumors regular

    Joined:
    Nov 30, 2009
    Location:
    Edinburgh, UK
    #3
    yeah...i actually just noticed this about 10 minutes ago...that's embarrassing.

    Are you saying:
    Code:
    [returnDict setObject:[[NSNumber alloc]initWithShort:mod] 
    
    would become:
    Code:
    [[returnDict setObject:[[NSNumber alloc]initWithShort:mod]autorelease]
    
     
  4. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
    Yes, but it's shorter to write:

    Code:
    [returnDict setObject:[NSNumber numberWithShort:mod]...
    EDIT: also you should not use valueForKey: unless you have a good reason to. Use objectForKey:
     

Share This Page