sohil
sohil

Reputation: 848

Combine Two NSMutableArray In Objective c

I have Two NSMutableArray Array I want to combine this array in to old one array.

How can i do this without any loop (for, while).

         NSMutableArray *oldArray = [[NSMutableArray alloc]init];
         [oldArray addObject:@"four"];
         [oldArray addObject:@"five"];
         [oldArray addObject:@"six"];

         NSMutableArray *newArray = [[NSMutableArray alloc]init];
         [newArray addObject:@"one"];
         [newArray addObject:@"two"];
         [newArray addObject:@"three"];

After Combine I want output like this :

         NSLog(@"After Combine : %@",oldArray);
         //Output : one, two, three, four, five, six

Upvotes: 0

Views: 107

Answers (3)

Willeke
Willeke

Reputation: 15589

Insert newArray in oldArray:

[oldArray insertObjects:newArray atIndexes:[[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, newArray.count)]]

Upvotes: 1

Ol Sen
Ol Sen

Reputation: 3368

This should do it.

newArray = [[newArray arrayByAddingObjectsFromArray:oldArray] mutableCopy];

for (NSString *str in newArray) {
    NSLog(@"%@", str);
}

output: [one,two,three,four,five,six]

wait, thats was copying into the new one.. :)

 oldArray = [[newArray arrayByAddingObjectsFromArray:oldArray] mutableCopy];

output: [one,two,three,four,five,six]

hahaha, possibly with the side effect that newArray is NSArray and has same content.
Check? Oh. newArray is still [one,two,three].

Upvotes: 0

Jawad Ali
Jawad Ali

Reputation: 14397

You can use addObjectesFromArray to get results

 [oldArray addObjectsFromArray: newArray];

Upvotes: 0

Related Questions