0

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps add that the first alloc/init is completely unnecessary, and the result discarded. - Also you have to use mutableCopy, otherwise tArray will be immutable.
2

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.

Comments

1

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.

2 Comments

It would be a memory leak only if you (still) use manual reference counting and not ARC.
yeah ofcourse, I wrote about memory leak only to get better understanding on how memory s allocated here. Editing, thanks.
1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.