简体   繁体   中英

Copy Object from NSMutableArray to another NSMutableArray

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?

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

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.

使用此代码:

NSMutableArray *array = [yourFirstArray mutableCopy];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM