2013-07-10 40 views
0

在我的應用程序中,我有一個開關,決定如何填充tableView。如果選擇了一面,它將顯示來自xml源的所有項目,而如果選擇了另一面,則只顯示已下載到設備的項目。首次打開應用程序時,默認情況下會顯示所有項目,並且所有行可以毫無問題地進行選擇,並且在選擇顯示下載時,所有選項都可以無問題地進行選擇;但是,當返回到「全部顯示」時,如果選擇更遠的表格單元格,則應用程序將崩潰。它只會在你選擇一個更下面的行數下載時崩潰,所以我懷疑這與numberOfRowsInSections調用有關,但我無法爲我的生活似乎修復它!UITableView崩潰行選擇

這裏是一個方法中我的代碼:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section   { 

if (showDownloadsSwitch.selectedSegmentIndex == 0){ 

    rows = itemsToDisplay.count; 
} 
else if (showDownloadsSwitch.selectedSegmentIndex == 1){ 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
    NSUserDomainMask, YES); 
    NSString *path = [[paths objectAtIndex:0] 
    stringByAppendingPathComponent:@"downloads"]; 

    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path 
    error:&error]; 
    rows = fileList.count; 
} 
return rows; 
} 

編輯:

我能夠多一點檢查後進行修復。原來我在[downloads objectAtIndex:indexPath.row]中檢查了一個文件,然後確保表中填充了下載,而不是所有項目。感謝大家的幫助!

+2

你是什麼確切的錯誤? –

+0

你也應該添加你的選擇邏輯。看起來你的'rows'變量沒有在本地聲明......這是一個成員變量嗎? – Justin

+0

它撞上了什麼?請提供確切的錯誤,並考慮添加堆棧跟蹤。 –

回答

0

您可能不應該使用屬性來存儲行。使其成爲局部變量。如果您需要訪問委託方法外的表中的行數,請再次單獨運行邏輯。

然而,fileList局部變量看起來應該是一個屬性。你在didSelectRowAtIndex方法中引用了一個simar數組,對嗎?那裏可能有差異嗎?

更新:

- (void)viewDidLoad 
{ 

    self.itemsToDisplay  = ... 
    self.fileList   = ... 
    self.showDownloadsSwitch = ... 

    [self.showDownloadsSwitch addTarget:self.tableView 
           action:@selector(reloadData) 
        forControlEvents:UIControlEventValueChanged]; 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 2; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (section == 0 && self.showDownloadsSwitch.selectedSegmentIndex == 0) 
    return self.itemsToDisplay.count; 

    if (section == 1 && self.showDownloadsSwitch.selectedSegmentIndex == 1) 
    return self.fileList.count; 

    return 0; 
} 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.section == 0) 
    [self.itemsToDisplay objectAtIndex:indexPath.row]; 
    else 
    [self.fileList objectAtIndex:indexPath.row]; 
} 
+0

這是唯一使用fileList變量的地方,我使用了一個單獨的數組,它是一個屬性,但在didSelectRowAtIndexPath方法中使用相同的邏輯實例化。如果有差異,是否會導致這個特殊問題?在我看來,根據我的代碼,當我訪問這個數組時,問題在於它應該訪問所有提要項的其他數組。它似乎能夠在第一次切換選項時從第一行計數切換到第二行,但無法返回到第一行計數... –

+0

您的錯誤表明您嘗試訪問索引(該行)的數組數量與您期望的數量不同。我只是用一個例子更新了答案。 –

0

嘗試包括這一個。

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section 
{ 
    UIView *view=[[UIView alloc] init]; 
    return view; 
} 

如果選擇了第二選項,它將不允許顯示更多行以供選擇。

0

我覺得你的數組爲空讓試試下面的場景

NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path 
    error:&error]; 
if(fileList) 
{ 
    rows = fileList.count; 
} 
else 
{ 
// handle your error 
}