Reputation: 279
I found very strange issue on NSMutableArray
. First I create 1 NSMutableArray
(arrA
) and add object to it. Then I create another NSMutableArray
(arrB
).
Then I add arrA
to arrB
. Finally when I update data inside arrB
then arrA
update also. Code like below
[arrA addObjectsFromArray:dataBack];
[arrB removeAllObjects];
[arrB addObjectsFromArray:arrA];
After this for
loop I found data arrA
change like arrB
for (int i = arrB.count-1; i >= 0; i--) {
if (itemExLong > 0 && [[[arrB objectAtIndex:i] objectForKey:@"IM_QtyPriceEx"] doubleValue] > itemExLong)
{
itemExLong = [[[arrB objectAtIndex:i] objectForKey:@"IM_QtyPriceEx"] doubleValue] + itemExLong;
itemTaxLong = [[[arrB objectAtIndex:i] objectForKey:@"IM_QtyTax"] doubleValue] - itemTaxLong;
data = [arrB objectAtIndex:i];
[data setValue:[NSString stringWithFormat:@"%0.2f",itemExLong] forKey:@"IM_PriceEx"];
[data setValue:[NSString stringWithFormat:@"%0.2f",itemTaxLong] forKey:@"IM_QtyTax"];
[arrB replaceObjectAtIndex:i withObject:data];
break;
}
}
When I replaceObjectAtIndex
, I found arrA
data change. Please Help.
Upvotes: 0
Views: 39
Reputation: 14477
Both arrays contain pointers to same underlaying objects. So if you will change an object using a pointer in any array it will change object (not the pointer) and that object is same for both arrays. If you want to keep to different copies of objects make a copy of objects before manipulating them.
If you have custom class then you add copying functionality you can do that by implementing NSCopying
protocol, to learn more about NSCopying
Upvotes: 2