2012-02-27 62 views
0

我有一個循環,它創建一個鍵(基於字母表)併爲空數組賦值。無法將值添加到NSMutableDictionary

-(id)init 
{ 
    if (self = [super init]){ 
     addressbook=[[NSMutableDictionary alloc] init]; 
     //loop over the alphabetArray and add to an adressbook dictionary 
     for(char a = 'a'; a <= 'z'; a++){ 
      NSMutableArray * personenArrayTemp = [[NSMutableArray alloc] init]; 
      [addressbook setValue:personenArrayTemp forKey:[NSString stringWithFormat:@"%c", a]]; 
     } 
    } 
    return self; 
} 

接下來,我通過獲取的名字的第一個字母,並使用該查找在地址簿那封信的關鍵一人添加到我的地址。一旦找到我添加人物。

-(void)addAddressbook:(Persoon *)persoon{ 
    NSString *firstLetter = [persoon.naam substringToIndex:1]; 
    [[addressbook objectForKey:firstLetter] addObject:persoon]; 
    //NSLog(@"%@",firstLetter); 
    for(NSString *key in addressbook){ 
     NSLog(@"key=%@ , value=%@ ", key,[addressbook objectForKey:key]); 
    } 
} 

的NSLog的for循環剛返回此:

2012-02-27 16:26:20.152 Adresboek[4828:503] key=p , value=(
) 
2012-02-27 16:26:20.155 Adresboek[4828:503] key=c , value=(
) 
2012-02-27 16:26:20.190 Adresboek[4828:503] key=b , value=(
) 
. 
. 
. 
2012-02-27 16:26:20.223 Adresboek[4828:503] key=o , value=(
) 

所有值都是空的。

解決,它返回一個大寫字母

+0

嘗試'爲(在[地址簿allKeys]的NSString *鍵){' – 2012-02-27 15:47:15

+0

我得到相同的結果 – Stofke 2012-02-27 15:52:13

+0

另一個奇怪的事情:你添加非常相同的陣列實例的每個字母(因此所有的信件共享相同的陣列)。我希望看到所有字母都重複同一個人。字典是否重置在某個地方? – Dirk 2012-02-27 16:01:06

回答

1

首先,要添加相同NSMutable陣列實例都在你的NSDictionary的關鍵。因此,無論您添加什麼(或不添加),輸出中每個鍵的結果都將始終相同。如果不是您打算什麼,那麼你需要將你的循環內的臨時創建陣列:現在

//loop over the alphabetArray and add to an adressbook dictionary 
for(char a = 'a'; a <= 'z'; a++){ 
    NSMutableArray * personenArrayTemp = [[NSMutableArray alloc] init]; 
    [addressbook setValue:personenArrayTemp forKey:[NSString stringWithFormat:@"%c", a]]; 
} 

,問題是爲什麼是越來越添加什麼。我懷疑如果你看看[addressbook objectForKey:firstLetter]的值,它可能是nil,所以當你將對象添加到它時,什麼都不會發生。很難說出爲什麼會發生這種情況:您必須查看persoon.naam中傳遞給函數的內容以及返回到firstLetter變量的內容。是否firstLetter與您在字典中用作索引的字符串真的是相同的字符串?