2011-10-24 59 views
0

現在的問題是:如何創建一個由NSArray的NSArray組成的NSDictionary,用於鍵值和一堆int的值?

NSArray * alphabets = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",nil]; 
NSDictionary * alphaToNum = [NSDictionary dictionaryWithObject:alphabets forKey:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]; 
//I know above line meant to not work I just brought it here as an example 

我怎麼可以創建就像上面這是工作的一本字典?

回答

2

您只能在NSDictionary中使用對象作爲鍵或值,因此必須使用NSNumber作爲整數鍵的包裝。

NSMutableDictionary *alphaToNum = [NSMutableDictionary dictionary]; 
NSArray *alphabet = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",nil]; 
NSInteger index = 0; 

for(NSString *character in alphabet) 
{ 
    index ++; 
    [alphaToNum setObject:character forKey:[NSNumber numberWithInteger:index]]; 
} 
+0

哦,你是第一個=)刪除我的答案 – Nekto