Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to a NSArray

I know we could just use a NSMutableArray for the object, but what if that's not an option and we need to add new elements to an NSArray. How would we go about doing this?

My immediate answer would be to create a NSMutableArray with the original NSArray, add the new elements to it, then cast the NSMutableArray back to the original NSArray.

I was asked this in an interview and am curious what a correct solution might be, besides just use a NSMutableArray in the first place.

like image 375
Oscar Avatar asked Dec 02 '22 20:12

Oscar


1 Answers

NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", nil];

array = [array arrayByAddingObject:@"Three"];

or

NSArray *newArray = [NSArray arrayWithObjects:@"Three", @"Four", nil];

array = [array arrayByAddingObjectsFromArray:newArray];
like image 153
Fogmeister Avatar answered Dec 14 '22 15:12

Fogmeister