如何在目标c

时间:2016-08-26 10:11:35

标签: ios objective-c nsmutablearray

我是iOS新手。我这样做

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

它给我输出像 ACEBDE

但我需要输出 ABCDEF

任何提示

4 个答案:

答案 0 :(得分:0)

我现在试了。我明白了。检查下面的答案。你必须简单地使用sortDescriptor。

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

NSArray *sortedArray = [animals sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSLog(@"The sortedArrays are - %@",sortedArray);

打印结果

The sortedArrays are - (
A,
B,
C,
D,
E,
F
)

答案 1 :(得分:0)

只需循环播放

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

这适用于所有类型的数组。

答案 2 :(得分:0)

试试这个 -

{{1}}

答案 3 :(得分:0)

添加另一个答案只是为了好玩。

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

NSInteger minCount;
NSMutableArray *maxArray;

if (arr1.count < arr2.count) {
    minCount = arr1.count;
    maxArray = arr2;
}
else {
    minCount = arr2.count;
    maxArray = arr1;
}

for (int i = 0; i < minCount; i++) {
    [animals addObject:arr1[i]];
    [animals addObject:arr2[i]];
}

NSInteger pendingItemsLength;
if ((pendingItemsLength = maxArray.count - minCount)) {
    [animals addObjectsFromArray:[maxArray subarrayWithRange:NSMakeRange(minCount, pendingItemsLength)]];
}

这比接受的答案更有效,因为它避免了for循环中的条件。