how to add object multi NSArray in one NSMutableArray
11,933
Solution 1
You can use addObjectsFromArray: from NSMutableArray class
all = [[NSMutableArray alloc]init];
[all addObjectsFromArray:animal];
[all addObjectsFromArray:color];
Solution 2
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];
Solution 3
I am using this:
all = @[animal, color];
But you must convert the array "all" from NSMutableArray
to NSArray
.
Solution 4
all = [[all arrayByAddingObjectsFromArray: animal] mutableCopy];
all = [[all arrayByAddingObjectsFromArray: color] mutableCopy];
Author by
janatan
Updated on June 04, 2022Comments
-
janatan almost 2 years
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 }
-
tkanzakic about 11 yearsthere is an error in the initialization, you miss a '[', and you can use
initWithArray
avoiding one instruction -
Aravindhan about 11 years@duDE : In fact I was sent to human verification also while answering this question. :)
-
Donal about 7 yearsI tried with same code.In this case my application getting crash with EXC_BAD_ACCESS