简体   繁体   中英

How to copy one NSMutableArray to another?

I have an nsmutablearray(xmlParseArray) having values firstname and id, I want to copy only firstname into another nsmutablearray(copyArray).

How can I do this?

Assumption: your xmlParseArray contains number of objects all of which have a firstname property and and an id property

NSMutableArray* nameArray = [[xmlParseArray valueForKey: @"firstname"] mutableCopy];

// nameArray is an array you own.

-valueForKey: when sent to an array causes the message -valueForKey: to be sent to each of its elements and a new array to be constructed from the return values. The -mutableCopy ensures that the result is then turned into a mutable array as per your question.

NSMutableArray *arr = [NSMutableArray arrayWithObject:[copyArray objectAtIndex:0]];

or

[arr addObject:[copyArray objectAtIndex:0]];
  [arr addObject:[copyArray objectAtIndex:1]];

I'm guessing you mean that the first array, xmlParseArray , contains a list of NSDictionary objects which each have objects attached to the keys "firstname" and "id". One way to accomplish that would be like this:

NSMutableArray *copyArray = [[NSMutableArray alloc] initWithCapacity:[xmlParseArray count]];
for(NSDictionary *dict in xmlParseArray)
    if([dict objectForKey:@"firstname"])
        [copyArray addObject:[dict objectForKey:@"firstname"]];

// ...do whatever with copyArray...
[copyArray release];
NSMutableArray *newArray = [oldArray mutableCopy];

or

NSMutableArray *newArray = [NSMutableArray arrayWithArray:oldArray];

be aware that the objects in the array aren't copied, just the array itself (references to objects are maintained).

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