2011-07-31 4 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]]); 

편집을 : 귀하의 코멘트에 따르면, 당신이 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]); 

편집 : 당신은 값을 설정하는 NSMutableDictionary를 사용해야합니다. NSDictionary은 (는) 생성 된 후에 수정할 수 없습니다.

+0

컴파일러에서 numberWithInt : forKey를 찾을 수 없습니다 (반환 유형의 기본값은 id). –

+0

아마도 intValue 뒤에 닫는 괄호를 잊어 버렸을 것입니다. – omz