2011-04-06 112 views
0

我正在寻找一个多维数组的例子。我有一组缩略图(例如9个)和4个大拇指前排的tablecellview,给我3行。我想创建一个新的多维数组,它将保持3行,每行包含4个数组。多维数组

我看了很多过去3h的例子,但他们都似乎建议使用C风格的编码,我不知道如何去初始化他们或如果我需要释放。另外即时通讯在桌面视图中使用,所以即时通讯不知道如果生病需要使用NSarray或生病能够脱离与C风格的数组。任何建议感激地赞赏。

thumbnailarr[0][0] = 'img1.png'; 
thumbnailarr[0][1] = 'img2.png'; 
thumbnailarr[0][2] = 'img3.png'; 
thumbnailarr[0][3] = 'img4.png'; 

thumbnailarr[1][0] = 'img5.png'; 
thumbnailarr[1][1] = 'img6.png'; 
thumbnailarr[1][2] = 'img7.png'; 
thumbnailarr[1][3] = 'img8.png'; 

thumbnailarr[2][0] = 'img9.png'; 

回答

2

多维数组本质上是一个数组数组,NSArray可以有NSArrays作为它的内容。例如:

NSArray *thumbs= [NSArray arrayWithObjects: 
          [NSArray arrayWithObjects: @"img1.png",@"img2.png",@"img3.png",@"img4.png",nil], 
          [NSArray arrayWithObjects: @"img5.png",@"img6.png",@"img7.png",@"img8.png",nil], 
          [NSArray arrayWithObject: @"img9.png"],nil]; 

的访问是这样的:

[[thumbs objectAtIndex:i] objectAtIndex:j]; //same as thumbs[i][j] 
+0

我决定不使用C风格只是因为它需要更改我的代码中的许多其他东西。我没有完全按照你的建议,但它确实让我转到另一篇文章http://classroomm.com/objective-c/index.php?topic=3260.5; wap2,其中涉及的输入较少,并且不重要我正在处理的许多图像。谢谢大家的建议。 – 2011-04-06 12:12:10

1

的Objective-C没有什么特别的多维数组。你需要使用C二维数组,除非你想使用NSArray的NSArray。

 
NSString *thumbnailarr[3][4]; 

// initialize is easy if you include row-column in image names 
// like img10.png instead of img5.png, img01.png instead of img2.png 
for (NSInteger i = 0; i < 3; i++) { 
    for (NSInteger j = 0; j < 4; j++) { 
     thumbnailarr[i][j] = [[NSString alloc] initWithFormat:@"img%d%d.png", i, j]; 
    } 
} 

// in dealloc release them 
for (NSInteger i = 0; i < 3; i++) { 
    for (NSInteger j = 0; j < 4; j++) { 
     [thumbnailarr[i][j] release]; 
    } 
} 

而对于表格视图,行数是从tableView:numberOfRowsInSection:方法返回的结果。无论您是返回NSArray计数还是硬编码整数,都无关紧要。这意味着如果你从这个方法返回3,那么将会有3个单元格。 NSArray没有特别的依赖关系。

4

Objective-C中没有特殊的多维数组,但您也可以使用一维数组。

然后,您将使用基于模的计算将所需的行和列索引转换为数组索引:您将使用NSIndexPath来描述多维数组中的“坐标”。

NSUInteger nRows = 4; 
NSUInteger nCols = 3; 

-(NSInteger)indexForIndexPath:(NSIndexPath *)indexPath 
{ 
    // check if the indexpath is correct with two elements (row and col) 
    if ([indexPath length]!= 2) return -1; 
    NSUIntegers indexes[2]; 
    [indexPath getIndexes:indexes]; 
    return indexes[0]*nCols+indexes[1]; 
} 

-(NSIndexPath *)indexPathForIndex:(NSInteger)index 
{ 
    NSInteger indexes[2]; 
    NSInteger indexes[0] = index/nCols; 
    NSInteger indexes[1] = index%nCols; 
    return [NSIndexPath indexPathWithIndexes:indexes length:2] 
}