2011-07-31 22 views

答えて

5

辞書のキーと値はオブジェクト参照(id)である必要があります。したがって、整数をキーとして使用することはできません。代わりにNSNumberであなたの整数をラップする必要があります。

[NSNumber numberWithInt:5] 

その後、initWithObjects初期化子のいずれかを使用して、あなたのNSDictionaryを初期化することができます。値、キー、値、キー.. nil形式のキー/値を受け入れるinitWithObjectsAsKeys:イニシャライザを選択しました。

NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:15], [NSNumber numberWithInt:5], nil]; 

値にアクセスするには、あなたが同じことを行う必要があります。

NSLog(@"%@", [dict objectForKey:[NSNumber numberWithInt:5]]); 

EDIT:あなたのコメントによると、あなたがNSMutableDictionary、ないNSDictionaryのを使用しなければならないようです。同じことが、あなたの整数をラップに適用されていますが、setObjectメソッドを使用したいと思う:forKey方法:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; 
[dict setObject:[NSNumber numberWithInt:15] forKey:[NSNumber numberWithInt:5]]; 

はその助けをしていますか?

+0

あなたの質問にNSDictionaryが書かれています。必要なものはNSMutableDictionaryです。整数をラッピングすることについても同じことが適用されます。 setObject:forKeyメソッドを使用します。 – csano

4

NSNumberで包み:

int intKey = 1; 
int intValue = 2; 
[myDict setObject:[NSNumber numberWithInt:intValue] forKey:[NSNumber numberWithInt:intKey]]; 
NSLog(@"key: %i, value: %i", intKey, [[myDict objectForKey:[NSNumber numberWithInt:intKey] intValue]); 

はEDIT:あなたが値を設定するNSMutableDictionaryを使用する必要があります。 NSDictionaryは作成後に変更できません。

+0

コンパイラーは、#1行目で "numberWithInt:forKey not found(戻り値の型がidにデフォルト設定されています)"という文句を言います。 –

+0

おそらく、intValueの後ろに閉じ括弧を忘れています。 – omz

関連する問題