0

在我的应用程序中,我有一个决定如何填充 tableView 的开关。如果选择一侧,它将显示 xml 提要中的所有项目,而如果选择另一侧,它将仅显示已下载到设备的项目。首次打开应用时,默认显示所有项目,所有行都可以选择没有问题,选择显示下载时,也可以全部选择没有问题;但是,当返回“全部显示”时,如果您选择了更下方的表格单元格,则应用程序将崩溃。只有当您选择的行比下载的项目数更远时它才会崩溃,所以我怀疑这与 numberOfRowsInSections 调用有关,但我似乎无法终生修复它!

这是我在该方法中的代码:

- (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] 处检查文件,然后确保表格中填充了下载内容,而不是所有项目。感谢大家的帮助!

4

3 回答 3

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];
}
于 2013-07-10T21:19:37.530 回答
0

尝试包括这个。

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

如果选择了第二个选项,它将不允许显示更多要选择的行。

于 2013-07-11T04:58:57.157 回答
0

我认为你的数组是空的,让我们试试下面的场景

NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path
   error:&error];
if(fileList)
{
    rows = fileList.count;
}
else
{
 // handle your error
}
于 2013-07-11T05:20:07.963 回答