Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate one NSMutableArray to the end of another NSMutableArray

A simple answer to this super simple question would be great! Here is the pseudcode:

NSMutableArray *Africa = [Lion, Tiger, Zebra];
NSMutableArray *Canada = [Polar Bear, Beaver , Loon];

NSMutableArray *Animals = *Africa + *Canada;

What I want to end up with:

Animals = [Lion, Tiger, Zebra, Polar Bear, Beaver, Loon];

What is the proper syntax to achieve this in Objective-C/ Cocoa?

Thanks so much!

like image 554
Eric Brotto Avatar asked Aug 23 '10 15:08

Eric Brotto


People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSMutableArray?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

Is NSArray ordered?

In Objective-C, arrays take the form of the NSArray class. An NSArray represents an ordered collection of objects. This distinction of being an ordered collection is what makes NSArray the go-to class that it is.

How do I add elements to an array in Objective C?

Creating an Array Object For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; The above code creates a new array object called myColors and initializes it with four constant string objects containing the strings "Red", "Green", "Blue" and "Yellow".


1 Answers

To create an array:

NSMutableArray* africa = [NSMutableArray arrayWithObjects: @"Lion", @"Tiger", @"Zebra", nil];
NSMutableArray* canada = [NSMutableArray arrayWithObjects: @"Polar bear", @"Beaver", @"Loon", nil];

To combine two arrays you can initialize array with elements of the 1st array and then add elements from 2nd to it:

NSMutableArray* animals = [NSMutableArray arrayWithArray:africa];
[animals addObjectsFromArray: canada];
like image 165
Vladimir Avatar answered Oct 27 '22 02:10

Vladimir