开发者

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!


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];


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜