I have an NSMutableArray called container, and a NSMutableArray called temp. To make temp, i have:
temp = container;
Now whenever i change something in temp, for example:
[temp replaceObjectAtIndex:1 withObject:[NSNumber numberWithFloat:0.9f]];
It changes temp, and also changes the value in container too. Why is this? And how can i stop it?
EDIT: Ok, i changed it to temp = [[container mutableCopy] autorelease]; as suggested
Now the problem is that this line:
[temp replaceObjectAtIndex:1 withObject:[NSNumber numberWithFloat:0.9f]];
still changes the value in container.
You’re just setting
tempto share the same pointer ascontainer.To get a true (independent) copy of container use this:
Objective-C (being an object oriented derivative of C) uses C pointers for object variables (that’s the
*inNSMutableArray *container).And a c pointer simply points to an address in memory. So if you were to set
tempto the same value ascontainerviatemp = container;you just assigning temp the same address ascontaineris already pointing at. Changing either of both will thus also change the other. Or more correct: you’re actually just changing one of them. It just looks like you’re changing both, but in fact you’re just having two pointers pointing at the same object instance, whch is being changed.