Search code examples
objective-cnsdictionarynsnumberprimitive

Objective-C: Can't put primitives in NSDictionary and retrieve them successfully


I know I can't put them in directly, but I have to convert them to an NSNumber, for example. I am converting them to NSNumbers, and then putting them in the dictionary. I immediately log the keys I'm populating, and they are blank.

Here's an example:

- (NSDictionary*) dictionaryFromWrestler
{
    /* 
     * Used ot create a dictionary from the instance of the wrestler
     * Can be used to send and receive wrestlers through notification center
     */
    NSDictionary* dictionary;

    NSNumber* _score = [NSNumber numberWithInt:score];


    dictionary = [NSDictionary dictionaryWithObjectsAndKeys:firstName, @"firstName", lastName, @"lastName", fullName, @"fullName", shortName, @"shortName", team, @"team", seed, @"seed", actualWeight, @"actualWeight", dob, @"dob", club, @"club", hometown, @"hometown", state, @"state", grade, @"grade", extraField, @"extraField",  phone, @"phone", address, @"address", zip, @"zip", record, @"record", gradeAbbr, @"gradeAbbr", twid, @"twid", teamId, @"teamId", position, @"position", _score, @"score", [NSNumber numberWithInt:teamScore], @"teamScore", [NSNumber numberWithInt:period1Score], @"period1Score", [NSNumber numberWithInt:period2Score], "@period2Score", [NSNumber numberWithInt:periods], @"periods", [NSNumber numberWithBool:hasRidingTime], @"hasRidingTime", nil];

NSLog(@"dictionaryFromWrestler Score: %@", lastName);
NSLog(@"dictionaryFromWrestler Score: %i", score);
NSLog(@"dictionaryFromWrestler Score: %@", _score);
NSLog(@"dictionaryFromWrestler Score: %d", [[dictionary objectForKey:@"score"] intValue]);
NSLog(@"dictionaryFromWrestler Score: %@", [dictionary valueForKey:@"score"]);
NSLog(@"dictionaryFromWrestler Score: %@", [dictionary valueForKey:@"lastName"]);

    return dictionary;
}

My log looks like this:

2012-05-18 17:46:53.117 Wrestling Tools[31509:403] dictionaryFromWrestler Score: Brown
2012-05-18 17:46:53.117 Wrestling Tools[31509:403] dictionaryFromWrestler Score: 2
2012-05-18 17:46:53.117 Wrestling Tools[31509:403] dictionaryFromWrestler Score: 2
2012-05-18 17:46:53.117 Wrestling Tools[31509:403] dictionaryFromWrestler Score: (null)
2012-05-18 17:46:53.117 Wrestling Tools[31509:403] dictionaryFromWrestler Score: (null)
2012-05-18 17:46:53.117 Wrestling Tools[31509:403] dictionaryFromWrestler Score: Brown

As you can see, the primitives fail, but the objects work. What the heck?


Solution

  • The method -[NSDictionary dictionaryWithObjectsAndKeys:] stops processing its list of arguments when it hits a nil value. This doesn't just mean the literal nil you wrote; it's any argument that evaluates to nil (because, of course, the method can't tell the difference).

    So, surely one of the values in your looong list, prior to _score, is nil and is thus prematurely truncating the list. Therefore, the dictionary really doesn't have a key "score".