6

以下に、ドキュメント ディレクトリのファイルを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;
    }
4

3 に答える 3

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];

そして、次のように処理する必要があります。

-(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;
}

ファイルがないとき、またはデータが読み込まれているときに 1 を返すことに注意してください。そのセルに「データを読み込んでいます...」または「レコードが見つかりません」などのメッセージを表示できます。ロジックが適切に実装されていない場合に矛盾が生じる可能性があるため、そのセルにを必ず設定してくださいuserInteractionEnabledNO

于 2013-06-30T17:17:46.993 に答える
2

tableView:numberOfRowsInSection:呼び出すと filePathsArray が nil なので、このメソッドからは 0 が返されます。あなたのコードは基本的に「私のtableViewには行がありません」と言っています。
また、tableView に行がない場合、tableView はセルを要求しません。したがって、配列を埋めるメソッドは呼び出されません。

次の 3 行のコードを- (void)viewDidLoadまたはに移動します。- (void)viewWillAppear:(BOOL)animated

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
于 2013-06-30T17:17:12.057 に答える