Objective-C:如何将文件目录中的文件列入UITableView?

use*_*879 5 objective-c uitableview ios

下面我有一些代码将文件目录中的文件列入UITableView.但是,代码没有正常工作,一旦我在我的设备上测试,即使文档目录中有文件,也没有列出所有显示只显示一些空白单元格的内容.这是我目前使用的代码:

NSArray *filePathsArray;

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [filePathsArray count];   
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
        }
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
        cell.textLabel.text = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]];
        return cell;
    }
Run Code Online (Sandbox Code Playgroud)

Jam*_*far 4

在您的代码中,您正在填充数组cellForRowAtIndexPath:,显然

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

之前被调用过cellForRowAtIndexPath。因此,您需要在重新加载表视图之前初始化数组的内容。将以下行放入 ViewDidLoad 或 viewWillAppear 方法中:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
Run Code Online (Sandbox Code Playgroud)

你应该做这样的处理:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   if(!isDataLoading)  // if data loading has been completed, return the number of rows ELSE return 1
   {

       if ([filePathsArray count] > 0) 
          return [filePathsArray count];
       else 
          return 1;
    }

  return 1;
}
Run Code Online (Sandbox Code Playgroud)

请注意,当没有文件或正在加载数据时,我将返回 1,您可以在该单元格中显示“正在加载数据...”或“未找到记录”之类的消息。确保将该单元userInteractionEnabled格设置NO为 ,否则如果逻辑未正确实现,可能会导致不一致。