2009-10-22 54 views
12

下面的代碼片段:如何在NSDictionary中正確設置整數值?

NSLog(@"userInfo: The timer is %d", timerCounter); 

NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:timerCounter] forKey:@"timerCounter"]; 

NSUInteger c = (NSUInteger)[dict objectForKey:@"timerCounter"]; 
NSLog(@"userInfo: Timer started on %d", c); 

線沿線的產生輸出:(FWIW,timerCounter是NSUInteger)

2009-10-22 00:36:55.927 TimerHacking[2457:20b] userInfo: The timer is 1 
2009-10-22 00:36:55.928 TimerHacking[2457:20b] userInfo: Timer started on 5295968 

我敢肯定,我失去了一些東西相當明顯,只是不確定它是什麼。

回答

22

您應該使用intValue從接收到的對象(NSNumber),而不是使用強制:

NSUInteger c = [[dict objectForKey:@"timerCounter"] intValue]; 
+5

實際上,對於NSUInteger,你應該使用'-unsignedIntegerValue'。 – 2009-10-22 06:14:25

+2

(和'+ [NSNumber numberWithUnsignedInteger:]'創建NSNumber,如果它確實是無符號的。) – Wevah 2009-10-22 21:54:21

+0

你可以用'@(timerCounter)'代替'[NSNumber numberWithInteger:timerCounter]' – fpg1503 2016-12-19 02:58:56

11

字典總是存儲對象。 NSInteger和NSUInteger不是對象。你的字典存儲了一個NSNumber(記得[NSNumber numberWithInteger:timerCounter]?),它是一個對象。正如epatel所說,如果你想要一個NSUInteger,你需要詢問NSNumber的unsignedIntegerValue

0

或者這樣用文字:

NSUInteger c = ((NSNumber *)dict[@"timerCounter"]).unsignedIntegerValue; 

必須轉換爲NSNumber的第一爲目標,從字典中拉將id_nullable,因此不會給值轉換方法作出迴應。

相關問題