NSDictionary allKeys error

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

  1. spaceman816 macrumors member

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

    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


    Jan 10, 2005
    Dallas, TX
    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.


    some links for future reference:
  3. mccannmarc macrumors 6502


    Aug 15, 2008
    Manchester, UK
    You cannot hold primitive types in an NSArray or an NSDictionary, in the
    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
    NSLog([NSString stringWithFormat:@"%d", [ranges objectAtIndex:0].intValue]);

Share This Page