开发者

iphone: problem in NSMutableArray and NSMutableDictionary

Dont know whats wrong with this array

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

NSMutableDictionary *aLocation=[[NSMutableDictionary alloc] init];
[aLocation setObject:@"26.8465108" forKey开发者_JS百科:@"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];

but every time I remove all objects from aLocations dictionary those values get deleted from locations array as well.

Please help me in this


This behaviour is correct and you can't reuse NSMutableDictionary as you do: NSMutableArray does not copy objects it contains - it just stores pointers to those objects. So if an object you added to array changes then array has pointer to that changed object.

To fix your code create NSMutableDictionary instance each time you need to add it to array (or create immutable dictionary if you actually don't need mutable object):

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜