Reputation: 31627
I have below code...
NSMutableArray *tArray = [[NSMutableArray alloc] init];
tArray = mainArray;
[tArray removeObjectAtIndex:mainArray.count-1];
In mainArray I have 4 items.
When I run above code what I was expecting is as below.
mainArray >> 4 items
tArray >> 3 items
However I am getting result as below.
mainArray >> 3 items (this is WRONG)
tArray >> 3 items
Any idea why the object is getting removed from main array when I do the removal from main array.
Upvotes: 0
Views: 83
Reputation: 171
This line
tArray = mainArray;
copies the reference of mainArray
to tArray
that is why the data is removed from both the array tArray
and mainArray
.
Try
tArray = [[NSmutableArray alloc] initWithArray:mainArray];
Upvotes: 1
Reputation: 17043
tArray and mainArray are pointers. And they refer to the same array in your case. You should use
NSMutableArray *tArray = [mainArray mutableCopy];
to really copy array.
[[NSMutableArray alloc] init]
is not necessary since result will be discarded.
Upvotes: 4
Reputation: 9484
This can be explained like this:
NSMutableArray *tArray = [[NSMutableArray alloc] init];
implies a new object is created.
tArray -> [a new object]
tArray = mainArray;
implies both mainArray and tArray now refers to same object
tArray -> [main array object] <- mainArray
and no one refers to [a new object], that is a memory leak in case of non-ARC as well.
Upvotes: 1
Reputation: 25459
The line
tArray = mainArray;
set the tArray to be exactly the same array as mainArray, they point to the same object in memory so when you make changes to one of them the object in memory will be changed and all instances which points to it will see that change.
You should copy the array if you want to have two separate object.
Upvotes: 2