简体   繁体   English

如何将一个NSMutableArray复制到另一个?

[英]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). 我有一个具有名字和ID值的nsmutablearray(xmlParseArray),我只想将名字复制到另一个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 假设:您的xmlParseArray包含许多对象,这些对象均具有firstname属性和id属性

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. -valueForKey:发送到数组时,将导致-valueForKey:消息发送到其每个元素,并根据返回值构造一个新数组。 The -mutableCopy ensures that the result is then turned into a mutable array as per your question. -mutableCopy可确保根据您的问题将结果转换为可变数组。

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". 我猜你的意思是,第一个数组xmlParseArray包含NSDictionary对象的列表,每个对象都有连接到键“ firstname”和“ 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). 请注意,不会复制数组中的对象,而只是复制数组本身(保留对对象的引用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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