iphone:如何使用其他数组中的对象创建数组

时间:2014-03-05 13:52:20

标签: ios iphone nsmutablearray nsarray

我有三个NSMutabelArrays,每个包含大约十个字符串,例如:

    1stArray = [NSMutableArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",nil];

    2ndArray = [NSMutableArray arrayWithObjects:@"j",@"k",@"l",@"m",@"n",@"o",@"p",nil];

    3rdArray = [NSMutableArray arrayWithObjects:@"q",@"r",@"s",@"t",@"u",@"v",@"w",nil];

现在我想用这3个NSMutableArray的前2个对象制作第4个NSMutabelArrays。 例如,我想要一个像这样的第四个数组:

4thArray = [@"a",@"b",@"j",@"k",@"q",@"r"]

如何实现这一目标?

3 个答案:

答案 0 :(得分:1)

我认为你正在寻找像这样的代码

int numElements = 2;
int numArrays = 3;

NSMutableArray * 4thArray = [NSMutableArray array];

for (int arrays = 0; arrays < numArrays; arrays++) {
    for (int count = 0; count < numElements; count++) {
        switch (arrays) {
            case 0:
                [4thArray addObject:[1stArray objectAtIndex:count]];
                break;
            case 1:
                [4thArray addObject:[2ndArray objectAtIndex:count]];
                break;
            case 2:
                [4thArray addObject:[3rdArray objectAtIndex:count]];
                break;
        }
    }
}

答案 1 :(得分:0)

看起来这样可以使用数组数组,或者可能是数组和字典的组合来解决,具体取决于您要实现的目标。你的问题的答案是微不足道的,所以我会指出你NSArray Reference,但你可能想要考虑不同的方法。

答案 2 :(得分:0)

喜欢这个

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",nil];
    NSMutableArray *secArray = [NSMutableArray arrayWithObjects:@"j",@"k",@"l",@"m",@"n",@"o",@"p",nil];
   NSMutableArray *thrdArray = [NSMutableArray arrayWithObjects:@"q",@"r",@"s",@"t",@"u",@"v",@"w",nil];

    NSMutableArray *fourthArr = [[NSMutableArray alloc] initWithObjects:[firstArray objectAtIndex:0],[firstArray objectAtIndex:1], [secArray objectAtIndex:0],[secArray objectAtIndex:1], [thrdArray objectAtIndex:0],[thrdArray objectAtIndex:1],nil];
    NSLog(@"%d", fourthArr.count);