2011-05-12 96 views
2

不要的問題知道什麼是錯這個陣列iphone:在NSMutableArray中和的NSMutableDictionary

NSMutableArray *locations=[[NSMutableArray alloc] init]; 

NSMutableDictionary *aLocation=[[NSMutableDictionary alloc] init]; 
[aLocation setObject:@"26.8465108" forKey:@"lat"]; 
[aLocation setObject:@"80.9466832" forKey:@"long"]; 
[locations addObject:aLocation]; 
[aLocation removeAllObjects] 

[aLocation setObject:@"26.846127990018164" forKey:@"lat"]; 
[aLocation setObject:@"80.97541809082031" forKey:@"long"]; 
[locations addObject:aLocation]; 
[aLocation removeAllObjects]; 

但我每次刪除aLocations所有對象時辭典這些值也會從位置陣列刪除。

請幫我在這

回答

4

此行爲是正確的,因爲你做你無法重複使用的NSMutableDictionary:NSMutableArray中不復制它包含的對象 - 它只是存儲指針這些對象。因此,如果您添加到數組的對象發生更改,則數組會指向該更改的對象。

要修復代碼中創建的NSMutableDictionary實例每次需要將其添加到陣列的時間(或創建不變的詞典,如果你真的不需要可變對象):

NSMutableArray *locations=[[NSMutableArray alloc] init]; 

NSMutableDictionary *aLocation= [NSMutableDictionary dictionaryWithObjectsAndKeys: 
         @"26.8465108", @"lat",@"80.9466832" ,@"long", nil ]; 
[locations addObject:aLocation]; 

aLocation= [NSMutableDictionary dictionaryWithObjectsAndKeys: 
       @"26.846127990018164", @"lat",@"80.97541809082031" ,@"long", nil ]; 
[locations addObject:aLocation]; 
+0

如何這個東西然後 – 2011-05-12 12:57:56

+0

你的答案是唯一正確的,讚美;-) PS:它也很容易創建一個可變的副本,然後再添加它[位置addObject:[[aLocation mutableCopy] autorelease]]]; – Jake 2011-05-12 13:15:59

+0

在沒有'aLocation'變量的情況下編寫上面的代碼 - 即[[位置addObject:[NSDictionary dictionaryWithObjectsAndKeys:...]']可能會更加地道。就我個人而言,我也傾向於使用'latitude'和'longitude'屬性創建一個'Coordinate'類。 – alastair 2011-05-12 14:27:48

1
NSMutableArray *locations=[[NSMutableArray alloc] init]; 

NSMutableDictionary *aLocation=[[NSMutableDictionary alloc] init]; 
[aLocation setObject:@"26.8465108" forKey:@"lat"]; 
[aLocation setObject:@"80.9466832" forKey:@"long"]; 
[locations addObject:aLocation]; 
[aLocation release]; 

NSMutableDictionary *aLocation1=[[NSMutableDictionary alloc] init]; 
[aLocation1 setObject:@"26.846127990018164" forKey:@"lat"]; 
[aLocation1 setObject:@"80.97541809082031" forKey:@"long"]; 
[locations addObject:aLocation1]; 
[aLocation1 release]; 
+0

我更喜歡弗拉基米爾的答案,因爲它解釋了爲什麼會發生。只是說。 – Jake 2011-05-12 13:15:37

+0

或者在字典添加併發布後,您可以重複使用相同的字典指針。 – Hagelin 2011-05-12 13:15:46

0
NSMutableArray *locations=[[NSMutableArray alloc] init]; 

NSMutableDictionary *aLocation= [NSMutableDictionary initWithObjectsAndKeys: 
         @"26.8465108", @"lat",@"80.9466832" ,@"long", nil ]; 

[locations addObject:aLocation]; 


aLocation= [NSMutableDictionary initWithObjectsAndKeys: 
       @"26.846127990018164", @"lat",@"80.97541809082031" ,@"long", nil ]; 

[locations addObject:aLocation]; 
相關問題