NSDictionary allKeys error

Discussion in 'iOS Programming' started by spaceman816, Aug 2, 2009.

  1. spaceman816 macrumors member

    Joined:
    Jul 29, 2009
    #1
    I am having a problem when running my NSDictionary eastDict through allKeys

    Code:
    NSBundle *eastBundle = [NSBundle mainBundle];
    NSString *eastPath = [eastBundle pathForResource:@"StreetEast" ofType: @"plist"];
    eastDict = [[NSDictionary alloc] initWithContentsOfFile:eastPath];
    NSLog([eastDict objectForKey:@"1"]);
    NSArray *ranges = [[eastDict allKeys] sortedArrayUsingSelector: @selector(compare: )];
    NSLog([NSString stringWithFormat:@"%d", [ranges objectAtIndex:0]]);
    
    The first NSLog runs correctly...the key 1, which should be the first sorted key returns the correct value, so I know that isn't the problem.
    But the second NSLog returns a strange 10 digit number (-1607296528). Any ideas as to why this is happening?
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    The first works "by accident". Instead of an NSString literal format string, you're passing the object returned by objectAtIndex as the first argument of NSLog. If this string happened to have a format specifier, you could have serious problems.
    The second fails because you're asking NSLog to print an NSObject *, which happens to be an NSString *, as a signed integer. You're getting the first four bytes of your pointer printed as a signed integer, just like you asked for. Use the %@ format specifier to print NSString *s and other objects.

    -Lee

    some links for future reference:
    http://developer.apple.com/document...rence/reference.html#//apple_ref/c/func/NSLog
    http://developer.apple.com/document...pecifiers.html#//apple_ref/doc/uid/TP40004265
     
  3. mccannmarc macrumors 6502

    mccannmarc

    Joined:
    Aug 15, 2008
    Location:
    Manchester, UK
    #3
    You cannot hold primitive types in an NSArray or an NSDictionary, in the
    Code:
    NSLog([NSString stringWithFormat:@"%d", [ranges objectAtIndex:0]]);
    line you are trying to display an object as a signed int. either replace the %d with a %@ or use something like
    Code:
    NSLog([NSString stringWithFormat:@"%d", [ranges objectAtIndex:0].intValue]);
     

Share This Page