13

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!

2 Answers 2

49

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];
Sign up to request clarification or add additional context in comments.

Comments

1

Based on Vladimir's answer I wrote a simple function:

NSMutableArray* arrayCat(NSArray *a, NSArray *b)
{
    NSMutableArray *ret = [NSMutableArray arrayWithCapacity:[a count] + [b count]];
    [ret addObjectsFromArray:a];
    [ret addObjectsFromArray:b];
    return ret;
}

but I haven't tried to find out if this approach is faster or slower than Vladimir's

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.