-1

Here is my arrayResult (NSMutableArray) :

<__NSArrayM 0x7fd160e365f0>(
{
    Amount = 00;
    Carat = 00;
    Color = D;
    Cut = EX;
    Discount = 00;
    IsSelected = 1;
    Quality = IF;
    Rate = 00;
    Shape = RBC;
    StoneNo = "";
    Symme = EX;
},
{
    Amount = 00;
    Carat = 00;
    Color = D;
    Cut = EX;
    Discount = 00;
    IsSelected = 0;
    Quality = IF;
    Rate = 00;
    Shape = RBC;
    StoneNo = "";
    Symme = EX;
}
)

Now I want to copy an object from NSMutableArray to another NSMutableArray. For that I use this:

    [arrayCopyRow addObject:[arrayResult objectAtIndex:0]];

But I store its address also, so if I change ValueAtIndex 0 that it automatically change it's copied object.

How do I prevent this? How do I create a deep copy?

dan14941
  • 332
  • 3
  • 16
Dx Android
  • 61
  • 2
  • 13
  • 2
    What you are probably looking for is called `deep copy`: http://stackoverflow.com/questions/20072729/how-can-i-make-a-deep-copy-in-objective-c – luk2302 Apr 28 '16 at 12:26

3 Answers3

1

For this you will need a deep copy.

So you can first run:

NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:oldArray copyItems:YES];

This will create a one level deep copy according to Apples docs and items in the array will need to conform to the NSCopying protocol.

And if you only want one object copied you can use the newArray as a temporary array then create and initialise a new mutable array and move the object there like you were in the question.

To make sure any custom objects are copied as a deep copy with the above method, you need to add the copyWithZone: method in each class.

Rough example:

-(id) copyWithZone:(NSZone *) zone
{
    ObjectInArray *object = [super copyWithZone:zone];
    object.someValue = self.someValue;
    return object;
}
dan14941
  • 332
  • 3
  • 16
0

Put a copy of the element into the other array.

[arrayCopyRow addObject:[[arrayResult objectAtIndex:0] copy]];

or

[arrayCopyRow addObject:[[arrayResult objectAtIndex:0] mutableCopy]];

If you want copies of all elements you can do a deep copy like luk2302 said.

Willeke
  • 14,578
  • 4
  • 19
  • 47
-2

Use this code:

NSMutableArray *array = [yourFirstArray mutableCopy];
Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
balkaran singh
  • 2,754
  • 1
  • 17
  • 32