2013-03-15 32 views
-2

我是iOS開發新手。我不明白tableView的行爲。
爲了測試它,我做了兩個簡單的tableView應用程序,並且在兩種情況下,如果用戶向下滾動直到tableView結束,我已經用99999行加載了帶有標準代碼片段的tableView。cellForRowAtIndexPath:用於StoryBoard和XIB行爲和單元緩存機制?


應用1:TableViewWithStoryBoard的cellForRowAtIndexPath:代碼片段

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // for StoryBoard 

if (cell == nil) 
{ 
    static int i; 
    NSLog(@"New Cells created: %d ",++i);  

    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

// Configure the cell... 

cell.textLabel.text = [self.tableData objectAtIndex:indexPath.row]; 

return cell; 

}

問題1: 如果我刪除

forIndexPath:indexPath from 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // for StoryBoard 

則故事板仍樂趣cations在模擬器中正確嗎? 那爲什麼它提供了?

問題2: 爲什麼NSLog(@「New Cells created:%d」,++ i);永遠不會打印,即使我滾動到99999行,這是我的tableView結束?在什麼情況下NSLog會打印一些值?



應用2:TableViewWithNib的cellForRowAtIndexPath:代碼片段

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
// for Nib File 

if (cell == nil) 
{ 

    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

// Configure the cell... 

cell.textLabel.text = [self.tableData objectAtIndex:indexPath.row]; 

return cell; 

}

問題3: 如果我添加

forIndexPath:indexPath 

在XIB版本然後我的應用程序崩潰並引發異常?爲什麼這樣?

異常或錯誤: 終止應用程序由於未捕獲的異常「NSInternalInconsistencyException」,原因:「無法出列具有標識符細胞的細胞 - 必須註冊標識符的筆尖或一類或在一個情節串連圖板連接原型細胞'

+0

代碼有點不清楚,你可以把它放在一起嗎? – jcesarmobile 2013-03-15 12:45:14

+0

@jcesar - 嘿,我已經把所有的代碼放在一起,也提到了有問題的代碼部分。我已經使用StoryBoard和基於SingleView的App2製作了基於單視圖的App1和Nib – Robin 2013-03-15 13:15:36

回答

0

問題2:NSLog打印時創建第一行(我已與樣品項目測試和印刷24次öipad公司)在第一時間,所述時間的其餘部分不打印它因爲單元格已經存在並重用它們。

問題1 & 3:dequeueReusableCellWithIdentifierforIndexPath:indexPath在IOS 6是新的,你必須註冊標識符的小區xib或定製UITableViewCell類或在故事板連接原型細胞來使用它。

+0

我甚至在iPad模擬器上測試了NSLog(@「New Cells created:%d」,++ i);在(cell == nil){NSLog ....}的塊中。該塊永遠不會在基於iPhone或iPad的應用程序上調用。我已經通過加載99999行進行了測試。即使我已經滾動上下幾次。所以我的問題是什麼時候創建新的單元格。如果tableView繼續使用現有的單元格。 – Robin 2013-03-16 05:03:12

+0

NSLog將在iPad上打印23 + 2次,在iPhone上打印9 + 2。邏輯是(可見單元格+ 2),只有在將這兩個語句設爲static int i時纔會發生; NSLog(@「New Cells created:%d」,++ i);就在返回小區上方; – Robin 2013-03-16 05:13:48

+0

Tableview只創建可見單元格+ 2,然後重用它們,因此它不會創建更多單元格 – jcesarmobile 2013-03-16 08:43:30