2011-05-19 48 views
1

我知道使用arrayForRowAtIndexPath使用indexPath和row的基本思想,但我不確定通過二維數組的最佳方式。我創建了一個自定義單元格,可以將7個不同的字符串接受到7個持有者中,並且我創建了一個包含3行7個字符串的2D數組。 (3x7二維陣列)。有關如何設置cellForRowAtIndexPath自動通過此數組的任何建議?Objective C在cellForRowAtIndexPath中使用2D陣列

讓我進入更多細節。我的多維數組是包含7個字符串的數組的數組:(「土豆」,「0」,「1」,「2」,「3」,「4」,「5」)我的自定義單元格全部設置有7個子視圖(他們工作,我測試了一個數組)。在我所創建的自定義單元格的同一個班級,我已經創建了一個從測試陣列值分配給這些子視圖的方法:

- (void)setMyArray:(NSArray *)myArray 
{ 
    NSString *name = [myArray objectAtIndex:0]; 
    [nameLabel setText:name]; 
    [name release]; 
    NSString *numberA = [myArray objectAtIndex:1]; 
    [aLabel setText:numberA]; 
    [numberA release]; 
    NSString *numberB = [myArray objectAtIndex:2]; 
    [bLabel setText:numberB]; 
    [numberB release]; 
    NSString *numberC = [myArray objectAtIndex:3]; 
    [cLabel setText:numberC]; 
    [numberC release]; 
    NSString *numberD = [myArray objectAtIndex:4]; 
    [dLabel setText:numberD]; 
    [numberD release]; 
    NSString *numberE = [myArray objectAtIndex:5]; 
    [eLabel setText:numberE]; 
    [numberE release]; 
    NSString *numberF = [myArray objectAtIndex:6]; 
    [fLabel setText:numberF]; 
    [numberF release]; 
} 

在的viewController,我不得不稱之爲是:

[cell setMyArray:testList]; 

它的工作原理。我只是不確定如何用2D數組來做到這一點。

+0

這將取決於你如何配置你的2D陣列。 – 2011-05-19 03:27:04

+2

以上將最終崩潰。你過度釋放數組中的每個元素。調用'-objectAtIndex:'不是一個alloc,copy或retain,所以你不應該在結果上調用'release'。 – 2011-05-20 01:39:56

回答

0

我不知道到底是你的自定義單元格的代碼是什麼樣子,但你不只是做:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"]; 
    if (cell == nil) { 
     //... 
    } 

    [cell setMyArray:[self.myTwoDArray objectAtIndex:indexPath.row]]; 

    // and so on... 

而且,Rob的關於你的內存管理權。在您將它們從原始數組中取出時不要釋放這些對象。

+0

感謝Rob提供的內存管理技巧。是的,你是對的喬希,你的代碼很好。我想出了一些NSLogs,我的setMyArray工作得很好,不需要第二個objectAtIndex。它每次都收到一個數組。再次感謝你們。 – Plaidfox 2011-05-20 22:23:32

+0

另一個'NSArray'仍然是一個'NSArray',所以這就是當你要求'objectAtIndex'時得到的結果:'很高興能幫上忙! – 2011-05-20 22:24:54