开发者

List Contents of Directory in a UITableView

I am trying to list the contents of Ringtones directory in a TableView, however, I am only getting the last file in the directory in ALL cells, instead of file per cell. This is my code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    Profile_ManagerAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        cell.hidesAccessoryWhenEditing = YES;
    }

    cell.accessoryType = UITableViewCellAccessoryNone;
    //cell.textLabel.text = @"No Ringtones";
    //cell.textLabel.text = @"Test";

    NSString *theFiles;
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *fileList = [manager directoryContentsAtPath:@"/Test"];
    for (NSString *s in fileList){
        theFiles = s;
    }
    cell.textLabel.text = theFiles;

    return cell;
}

It loads fine, no errors, when I use NSLog it lists all the files in the directory just fine. I even tried [s obj开发者_运维知识库ectAtIndex:indexPath.row] but i get objectAtIndex: error. Anyone have any ideas?


I actually love asking questions on here, cause in less than 10 minutes, I answer my own question!

This is how I got the above code to work:

NSMutableArray *theFiles;
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:@"/Test"];
for (NSString *s in fileList){
    theFiles = fileList;
}
cell.textLabel.text = [theFiles objectAtIndex:indexPath.row];
return cell;

I just made the NSString an NSMutableArray, and that allowed me to use the objectAtIndex. Now to trim the file extension!


You should remove NSString,NSMutableArray and for loop.. the final code should be like this:

NSFileManager *manager = [NSFileManager defaultManager];
NSArray *fileList = [manager directoryContentsAtPath:@"/Test"];
cell.textLabel.text = [fileList objectAtIndex:indexPath.row];
return cell;

BTW, this fileList and manager created repeatedly for each cell.. So it is better to make it a global variable for UITableViewController and assign only 1


Your for loop is just iterating over the files and setting theFiles to the current path. So at the end of the loop, theFiles will just be the last string in the collection.

Try something like:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜