简体   繁体   中英

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:@"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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM