I know this is a common question on Stack Overflow, but unfortunately none have been able to lead me to my solution.
I'm trying to list the files in my documents directory in a UITableView
. (I also have another tableview displaying devices I'm connected to)
I know I'm getting this error because its saying that my array has 0 objects, and I'm trying to access the object at index 1.
But I have a file in my documents directory.
If I have 2 files, when I delete 1, I get this error. When the app is relaunched, it shows the UITableView
correctly with the file deleted.
I got my code from here: Objective-C: How to list files from documents directory into a UITableView?
this is my content:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (tableView == _tblConnectedDevices){
return [_arrConnectedDevices count];
}
if ([filePathsArray count] > 0){
return [filePathsArray count];
}
else
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == _tblConnectedDevices){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
}
cell.textLabel.text = [_arrConnectedDevices objectAtIndex:indexPath.row];
return cell;
} else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *last = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]];
NSString *last2 = [[last lastPathComponent] stringByDeletingPathExtension];
cell.textLabel.text = last2;
return cell;
}
}
My delete void:
-(IBAction)deleteFile:(id)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt", fileName]];
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error];
[_cellView reloadData];
}
Reload your filePathArray in deleteFile: Also set breakpoint and look how many files you have in array