2009-10-22 18 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); 

はの線に沿って出力生成:

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 

を(FWIW、タイマカウンタがNSUIntegerである。)

私は何かが欠けてると確信していますかなり明白で、それが何であるかだけは分かりません。

答えて

22

あなたは、受信したオブジェクト(NSNumber)からintValueを使用して、キャスト使用しないでください。

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

実際には、NSUIntegerの場合は、-unsignedIntegerValueを使用する必要があります。 –

+2

(NSNumberを作成するために '+ [NSNumber numberWithUnsignedInteger:]'が実際には署名されていない場合)。 – Wevah

+0

'[NSNumber numberWithInteger:timerCounter]'の代わりに '@(timerCounter)'を使うことができます。 – fpg1503

11

辞書ストアオブジェクトを。 NSIntegerとNSUIntegerはオブジェクトではありません。あなたの辞書は、オブジェクトであるNSNumber(覚えているのは[NSNumber numberWithInteger:timerCounter]?)を格納しています。だからepatelが言ったように、NSUIntegerが必要な場合は、unsignedIntegerValueのNSNumberに問い合わせる必要があります。

リテラルと
0

またはこのような:

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

あなたは辞書から引き出さオブジェクトはid_nullableになりますので、メソッドを変換した値に応答しませんように第1のNSNumberとしてキャストする必要があります。

関連する問題