2015-03-13 92 views
0

我在我的Documents目录中创建了两个文件夹。 我有一个UITableView显示文件夹中的项目。由于未捕获的异常'NSRangeException'而终止应用程序,原因:'*** - [__ NSArrayI objectAtIndex:]:索引0超出空数组边界

Subfolder = @"/Sent"; 

它给了我一个威胁1:上线的迹象SIGABRT:

NSString *last = [dataPath stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]]; 

我有两个表视图,这下面的代码一直工作正常,直到我加入了2个文件夹的文件目录。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    if (tableView == _tblConnectedDevices){ 
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"]; 

     if (cell == nil) { 
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"]; 
     } 

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

     return cell; 
    } else { 
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; 
     if ([filePathsArray count] == 0){ 
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentsDirectory = [paths objectAtIndex:0]; 
      NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",subFolder]]; 
      filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:dataPath error:nil]; 
     } 
     if ([filePathsArray count] > 0) { 

      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
      NSString *documentsDirectory = [paths objectAtIndex:0]; 
      NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",subFolder]]; 
      filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:dataPath error:nil]; 
      NSString *last = [dataPath stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]]; 
      NSString *last2 = [[last lastPathComponent] stringByDeletingPathExtension]; 
      cell.textLabel.text = last2; 
     } 
     return cell; 
    } 
} 

当我打开与它一个文件一个文件夹,它加载罚款,之后,如果我什么也没有打开文件夹,我得到下面的错误。 如果我第一次打开没有任何东西的文件夹,它很好,然后用它里面的东西打开文件夹,它很好,然后当我回到空文件夹时,再次出现相同的错误。 我在这里错过了什么?

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array' 
+1

添加执行断点,只是调试它。 – 2015-03-13 14:16:57

+0

尝试将'NSError'变量传递给您重新设置'filePathsArray'的行,并检查它是否报告任何错误。 – AMI289 2015-03-13 14:21:14

回答

1

您在方法中间重新指定filePathsArray。然后,您可以访问索引处的对象,而不检查它是否在数组边界内。这很可能不正确。

if ([filePathsArray count] > 0) { 
    /* ... */ 
    filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:dataPath error:nil]; 
    NSString *last = [dataPath stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]]; 

重新分配filePathsArray中的对象数可以小于indexPath.row。

+0

我很感谢你的时间,但我对iOS开发很陌生,可能很明显。在我的表格视图中显示文档中子文件夹的正确方法是什么? – Manesh 2015-03-13 15:23:07

相关问题