2011-04-06 110 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] 
}