如何在一个NSMutableArray中添加对象多NSArray

时间:2013-04-15 10:52:55

标签: ios objective-c nsmutablearray nsarray

我想将2个NSArray中的对象添加到NSMutableArray中。我不知道这件事。

这是我的代码:

@interface ViewController : UITableViewController
{
    NSArray *animal;
    NSArray *color;
    NSMutableArray *all;
}


@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    animal = [[NSArray alloc]initWithObjects:@"Lion",@"Tiger",@"Dog",@"Cat",@"Sheep",@"Wolf", nil];
    color = [[NSArray alloc]initWithObjects:@"Blue",@"Red",@"Yellow",@"Green",@"Black", nil];

    all = ??? ; //how to add object from animal and color array in all 
}

3 个答案:

答案 0 :(得分:18)

您可以使用addObjectsFromArray:

中的NSMutableArray
all = [[NSMutableArray alloc]init];
[all addObjectsFromArray:animal];
[all addObjectsFromArray:color];

答案 1 :(得分:4)

试试这个:

animal = [[NSArray alloc]initWithObjects:@"Lion",@"Tiger",@"Dog",@"Cat",@"Sheep",@"Wolf", nil];
color = [[NSArray alloc]initWithObjects:@"Blue",@"Red",@"Yellow",@"Green",@"Black", nil];

all = [[NSMutableArray alloc] init];
[all addObjectsFromArray:animal];
[all addObjectsFromArray:color];

答案 2 :(得分:1)

我正在使用它:

all = @[animal, color];

但您必须将数组“全部”从NSMutableArray转换为NSArray