我知道我不能直接放入它們,但我必須將它們轉換爲NSNumber
。我將它們轉換爲NSNumber
s,然後將它們放入字典中。我立即記錄了我正在填充的密鑰,並且它們是空白的。Objective-C:無法將基元放入NSDictionary中併成功檢索它們
下面是一個例子:
- (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;
}
我的日誌是這樣的:
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
正如你所看到的,原語失敗,但對象。有沒有搞錯?
我測試了你的代碼..它對我來說工作得很好...一定是你的編譯器或者其他問題。如果沒有任何工作,請嘗試重新安裝xcode。 – skytz
我在另一臺電腦上試過這個,並且有一個朋友嘗試了它。在所有情況下,字典的分數鍵都是空的。其他基元也會發生同樣的情況。我已經建立了一個幾乎沒有任何內容的小型項目,存在同樣的問題。這個問題可能是什麼? – Adam
我找到了一種方法來使它工作,但它對我沒有任何意義。如果我把字典變成可變的,它仍然不起作用。如果我還添加[字典setObject:_score forKey:@「score」];它確實有效。我不明白爲什麼Mutable會爲此做出改變,而且我不明白爲什麼獨立設置它可以在dictionaryWithObjectsAndKeys:不行的地方工作。爲什麼? @收集任何想法? – Adam