Reputation: 2249
I have oldArray that consists of many small arrays. Now i want to take one of these objects (one small array), modify it, and then (if the user hits a button) replace it. To do that:
Step 1 - I made a new array where I initialized newArray with that one small object.
openedCartProduct = nil;
openedCartProduct = [NSMutableArray array];
[openedCartProduct addObjectsFromArray: [SharedAppDelegate.myEngine.shoppingCart objectAtIndex:indexPath.row]];
Step 2 - Modify the array.
[[openedCartProduct objectAtIndex:0] setObject:[NSNumber numberWithFloat:[inputRabatLabel.text floatValue]] forKey:kRABAT_KEY];
Step 3 - replace the object in oldArray.
In step 2, the modification is ALSO happening in oldArray even before replacing the object. Am i missing something here?
Thanks in advance guys! :)
EDIT: The object modified is a small array consisting of a NSMutableDictionary at index 0 which I am modifying.
EDIT Seems like we need a DEEP COPY here. I found a solution that is a but of a hack, but works fine, and is simple enough:
openedCartProduct = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[SharedAppDelegate.myEngine.shoppingCart objectAtIndex:indexPath.row]]];
Upvotes: 2
Views: 354
Reputation: 604
You are copying a reference to the original small array. So that points to the small array in the first array when you change it. That contains all the original contents. If you want to alter it without changing it in the first array, you need to perform a copy, and in this case a deep copy, since it contains a mutableDictionary (that I assume you also want to copy).
Upvotes: 1