Naqi Naqi - 2 months ago 7
Objective-C Question

Objective-C: changing values of one NSMutableArray automatically change values of another NSMutableArray that is assigned to it

I am initializing two

NSMutableArrays
namely:

NSMutableArray *firstArray = [[NSMutableArray alloc] init];
NSMutableArray *secondArray = [[NSMutableArray alloc] init];


firstArray
has some values in it and
secondArray
has some values in it too.

Then I assigned
firstArray
to
secondArray
:

firstArray = secondArray;


Now if I make some changes in
firstArray
it will also affect
secondArray
. For example, if I replace or remove a value at certain index from
firstArray
then that value will also get removed from the
secondArray
.

So is there any way that changing in
firstArray
does not affect
secondArray
?

Answer

Try initialising both arrays like this

NSMutableArray *firstArray = [[NSMutableArray alloc] init];

NSMutableArray *secondArray = [[NSMutableArray alloc] initWithArray:firstArray];

Hope this helps.

Comments