Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

This can be explained like this:

  1. NSMutableArray *tArray = [[NSMutableArray alloc] init];
    implies a new object is created.
    tArray -> [a new object]

  2. 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.

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top