2013-06-30 2 views
5

Ниже у меня есть код, который перечисляет файлы из каталога моих документов в UITableView. Однако код работает некорректно, и как только я тестирую свое устройство, даже если в каталоге документов есть файлы, ничего не отображается, а отображается только несколько пустых ячеек. Вот код, я в настоящее время с помощью:Objective-C: Как перечислить файлы из каталога документов в 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

В вашем коде, вы заполняете массив в 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, когда нет файлов или если данные загружаются, вы можете отображать сообщение, подобное «Загрузка данных ...» или «Нет записей» в этой ячейке. Не забудьте установить userInteractionEnabled в NO для этой ячейки, иначе это может привести к несогласованности, если логика не будет выполнена должным образом.

+0

Почему «numberOfRowsInSection:' return '1', когда нет файлов? – rmaddy

+0

@maddy: В этой строке вы можете отобразить сообщение типа «Нет записей» или любое соответствующее сообщение, чтобы пользователь не путался. –

+0

@maddy: Убедитесь, что вы установили userInteractionEnabled в No для этой ячейки –

2

Когда tableView:numberOfRowsInSection: называется filePathsArray равна нулю, так что 0 возвращается из этого метода. Ваш код в основном говорит: «В моем табличном представлении нет строк».
И 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]; 
0
-(NSArray *)listFileAtPath:(NSString *)path 
{  
    int count; 

    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL]; 

    for (count = 0; count < (int)[directoryContent count]; count++) 
    { 
     NSLog(@"File %d: %@", (count + 1), [directoryContent objectAtIndex:count]); 
    } 
    return directoryContent; 
} 

-(void)viewDidLoad { 
    [super viewDidLoad]; 

    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    paths = [self listFileAtPath:documentsDirectory]; 
} 
Смежные вопросы