Muju Muju - 3 months ago 12
Objective-C Question

How to concatenate two mutable array like one element of first array and first element of second array in objective c

I am new in iOS.And I am doing like this

NSMutableArray* arr1 = [NSMutableArray arrayWithObjects: @"A", @"C", @"E", nil];
NSMutableArray* arr2 = [NSMutableArray arrayWithObjects: @"B", @"D", @"F", nil];
NSMutableArray* animals = [NSMutableArray arrayWithArray:arr1];
[animals addObjectsFromArray: arr2];


It give me output like
ACEBDE

But I need output like
ABCDEF

Any Hint

Answer

Just loop them

NSMutableArray* arr1 = [NSMutableArray arrayWithObjects: @"A", @"C", @"E", nil];
NSMutableArray* arr2 = [NSMutableArray arrayWithObjects: @"B", @"D", @"F", nil];
NSMutableArray* animals = [NSMutableArray new];

NSUInteger maxCount = arr1.count > arr2.count ? arr1.count : arr2.count;
for (int i = 0; i < maxCount; i ++) {
    if ([arr1 objectAtIndex:i]) {
        [animals addObject:[arr1 objectAtIndex:i]];
    }
    if ([arr2 objectAtIndex:i]) {
        [animals addObject:[arr2 objectAtIndex:i]]
    }
}

This will work for all types of arrays.