将NSarray转换为二维数组

时间:2013-12-10 15:42:28

标签: objective-c

我有一个一维数组,其中包含不同数量的对象(取决于用户输入)

NSArray被称为homePlayersArray。这可以包含2,3,5,6,4

我想把它转换成二维数组,例如。

{2,0},{3,},{5,0},{6,0},{4,0}

对象中的第一个值是NSarray(称为homepPlayersArray),第二个值是0。

获得此项的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

//Your original array
NSArray *homePlayersArray = [[NSArray alloc] initWithObjects:
                             [NSNumber numberWithInt:2],
                             [NSNumber numberWithInt:3],
                             [NSNumber numberWithInt:5],
                             [NSNumber numberWithInt:6],
                             [NSNumber numberWithInt:4],nil];

//For your 2D array
NSMutableArray *secondArray = [[NSMutableArray alloc] initWithCapacity:[homePlayersArray count]];

//populate as required
for(int i=0;i<[homePlayersArray count];i++){
    NSArray *tempArray = [[NSArray alloc] initWithObjects:[homePlayersArray objectAtIndex:i],[NSNumber numberWithInt:0], nil];
    [secondArray addObject:tempArray];
}

//print out some results to show it worked
NSLog(@"%@%@",@"secondArray first object value 0: ",[[secondArray objectAtIndex:0] objectAtIndex:0] );
NSLog(@"%@%@",@"secondArray first object value 1: ",[[secondArray objectAtIndex:0] objectAtIndex:1] );
NSLog(@"%@%@",@"secondArray second object value 0: ",[[secondArray objectAtIndex:1] objectAtIndex:0] );
NSLog(@"%@%@",@"secondArray second object value 1: ",[[secondArray objectAtIndex:1] objectAtIndex:1] );