iphone:在NSMutableArray中和的NSMutableDictionary

问题描述:

不要的问题知道什么是错这个阵列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所有对象时辞典这些值也会从位置阵列删除。

请帮我在这

此行为是正确的,因为你做你无法重复使用的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

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

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];