8

I want add object from 2 NSArray to NSMutableArray. I dont know about this.

this my code:

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

4 Answers 4

18

You can use addObjectsFromArray: from NSMutableArray class

all = [[NSMutableArray alloc]init];
[all addObjectsFromArray:animal];
[all addObjectsFromArray:color];
Sign up to request clarification or add additional context in comments.

2 Comments

there is an error in the initialization, you miss a '[', and you can use initWithArray avoiding one instruction
@duDE : In fact I was sent to human verification also while answering this question. :)
4

Try this:

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

1 Comment

I tried with same code.In this case my application getting crash with EXC_BAD_ACCESS
1

I am using this:

all = @[animal, color];

But you must convert the array "all" from NSMutableArray to NSArray.

Comments

1

all = [[all arrayByAddingObjectsFromArray: animal] mutableCopy];
all = [[all arrayByAddingObjectsFromArray: color] mutableCopy];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.