2012-07-05 88 views
0

如何通過indexPathsForVisibleRows讀取NSIndexpath數組的intValue?Objective-C visibleCells和indexPathsForVisibleRows

順便說一句,爲什麼visibleCells和indexPathsForVisibleRows在if(cell == nil)函數之前無法工作?

這裏是我的代碼:

cellForRowAtIndexPath方法中:

static NSString *identifierString; 
    UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:identifierString]; 

    // when I use visibleCells and indexPathsForVisibleRows here, the app crashes 

    if (cell == nil) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifierString] autorelease]; 
cell.accessoryType = UITableViewCellAccessoryNone;   
    } 

    // when I use visibleCells and indexPathsForVisibleRows here, the app works 

//cell implementation here 

    return cell; 
+0

感覺就像是很多方面的缺少問題的第二部分。你可以請求一些代碼,其中'if(cell == nil)'是? – dasblinkenlight 2012-07-05 18:29:45

+0

@das我已經添加了我的代碼。 – wagashi 2012-07-05 18:36:35

+0

如何在工作時閱讀他們的價值觀?你用這種方法試圖做什麼? – anuragbh 2012-07-06 02:37:05

回答

4

(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath是其中的tableview獲取與細胞填充。如果你試圖在可見單元格被創建之前引用它,這是在if語句中完成的,那麼應用程序會崩潰。 alloc命令爲要創建的單元分配了內存,然後使用某些參數進行初始化。這個方法被調用的次數與您在numberOfRowsInSection中指定的次數相同。

因此,您不會一次又一次重新創建所有單元格,if語句會檢查單元格是否存在,並且只有當它爲零時纔會創建新的單元格以取代該位置。

要獲得IndexPath的int行值,可以使用它的行屬性。例如:

NSArray indexArray = [self.tableView indexPathsForVisibleRows]; 
int i=0; 
while(i!=indexArray.count){ 
    //Log out the int value for the row 
    NSLog(@"%d", indexArray[i].row); 
    i++; 
} 

希望這有助於