Reputation: 8609
I have an app that allows users to save and open text files. Saving and opening files is fairly straightforward and easy, but I have to give the user an easy way to select a file to open. I decided to do this with a UITableView.
When the TableView loads in my view controller, my goal is to populate the TableView with the names of all of the user's text files from within the Documents folder (part of the iOS App Sandbox).
I have a general idea of how to do this:
Get the contents of the Documents folder and place it in an array
NSString *pathString = [[NSBundle mainBundle] pathForResource:@"Documents" ofType:@"txt"];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:pathString error:nil];
NSLog(@"Contents of directory: %@", fileList);
But this always returns: (null)
in the output window. What is the path for my app's document folder?
Place the array in the UITableView
I figured I'd use the numberOfRowsInSection
method to do this. Is this the right place for performing this type of operation? Of should I use a different method?
Finally, the app will get the value of the selected cell and use that value to open the file.
My main question here is: How can I place items (particularly the contents of directory) into an NSArray and then display that array in a UITableView?
Any help is much appreciated!
Upvotes: 1
Views: 2560
Reputation: 1098
You can get the path using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
You can get the contents of the directory using:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
As for displaying an NSArray in a UITableView, you should review Apple's documentation on UITableView Data Source protocol:
You use the cellForRowAtIndexPath method to actually populate the table, something like this would work:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyIdentifier"] autorelease];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [fileList objectAtIndex:indexPath.row]
return cell;
}
Upvotes: 3