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.
NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", nil];
array = [array arrayByAddingObject:@"Three"];
or
NSArray *newArray = [NSArray arrayWithObjects:@"Three", @"Four", nil];
array = [array arrayByAddingObjectsFromArray:newArray];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With