2017-10-17 87 views
0

我试图删除csv文件,同时删除单元格,但我发现了下一个错误,当我按下删除:UITableView - 如何删除文件时删除单元格?

Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]' * First throw call stack:

代码:

// 

/

/ CameraViewController.m 
// oFiOSstoryboard 
// 
// Created by Dorald on 24/05/15. 
// 
// 

#import "CameraViewController.h" 
#import "resultsDetailView.h" 


@interface CameraViewController() 

@property (strong, nonatomic) IBOutlet UITableView *data; 
@property (retain, nonatomic) IBOutlet UILabel *timeStamp; 
@property (strong,nonatomic) NSMutableArray *dirList; 
@property (nonatomic, assign) NSString *csvRow; 

@property (nonatomic, strong) NSMutableArray *dataArray; 


- (IBAction)didTapDeleteBtn:(id)sender; 


@end 

           ////////////////////////csv readder 
NSMutableArray *tableDataArray; 

NSString *bundleRoot = [[NSBundle mainBundle] bundlePath]; 
NSFileManager *manager = [NSFileManager defaultManager]; 
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot]; 
NSString *filename; 
NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
NSString *strPath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"csv"]; 
NSString *strFile = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil]; 
NSMutableArray *timeStampb = [[NSMutableArray alloc] init]; ; 
NSMutableArray *arrayToDelete = [[NSMutableArray alloc] init]; ; 
NSMutableArray *filePathsArray ; 
//NSMutableArray *dirList= [[NSMutableArray alloc] init]; ; 
NSString *currentcsvfile; 
NSString *csvfilenameSave; 

@implementation CameraViewController 



@synthesize data; 


- (void)viewDidLoad { 
[super viewDidLoad]; 
    // ////lista de documentos 

    self.data.scrollEnabled = YES; 

    self.data.delegate = self; 
    self.data.dataSource = self; 


    //filePathsArray =[[NSMutableArray alloc] init]; ; 


    self.data.allowsMultipleSelectionDuringEditing = YES; 


    self.dataArray = [[NSMutableArray alloc]init]; 
    NSInteger count = 100; 
    for (NSInteger i = count; i>=0; i--) { 
     NSString *title = [NSString stringWithFormat:@"cell %ld",i]; 
     [self.dataArray addObject:title]; 
    } 
    NSMutableArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 

    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    NSFileManager *manager = [NSFileManager defaultManager]; 
    NSMutableArray* fileList = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
    //--- Listing file by name sort 
    NSLog(@"\n File list %@",fileList); 

    //---- Sorting files by extension 
    NSMutableArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.csv'"]; 
    filePathsArray = [filePathsArray filteredArrayUsingPredicate:predicate]; 
    NSLog(@"\n\n Sorted files by extension %@",filePathsArray); 



    self.dirList = [filePathsArray mutableCopy]; 

    NSString *docPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 

    if (!strFile) { 
     NSLog(@"Error reading file."); 
    } 

    [timeStampb release]; 


     timeStampb = [[NSMutableArray alloc] initWithArray:[strFile componentsSeparatedByString:@"\,"]]; 
     // this .csv file is seperated with new line character 
     // if .csv is seperated by comma use "," instesd of "\n" 
    for(NSString *countryname in timeStampb) { 
     NSLog(@"%@", timeStampb); 

    } 


    } 


////////////////////////////////////////////////////////////////Delete csv files 
//- (IBAction)delet:(id)sender { 
// NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 
//  
// NSString *filePath = [docPath stringByAppendingPathComponent:@"jorge.csv"]; 
// NSError *error = nil; 
// [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; 
//} 




- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 


# pragma – mark table view DataSource Methods 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ 

    return 1; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [self.dirList count]; 

} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *simpleTableIdentifier = @"SimpleTableItem"; 



    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier ]; 
    if (cell == nil) { 

     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 

     UIColor* color = [UIColor colorWithRed:(254.0/255.0) green:(251.0/255.0) blue:(248.0/255.0) alpha:1]; 
     UIView *bgColorView = [[UIView alloc] init]; 

     bgColorView.backgroundColor = [UIColor colorWithRed:(253.0/255.0) green:(0.0/255.0) blue:(237.0/255.0) alpha:1]; 


     [cell setSelectedBackgroundView:bgColorView]; 
     cell.backgroundColor = color; 
    } 

    cell.textLabel.text = [timeStampb objectAtIndex:indexPath.row]; 
    cell.detailTextLabel.text = [self.dirList objectAtIndex:indexPath.row]; 


    cell.textLabel.textColor = [UIColor colorWithRed:(0.0/255.0) green:(0.0/255.0) blue:(0.0/255.0) alpha:1]; 
    cell.textLabel.font=[UIFont systemFontOfSize:8.0]; 

    cell.detailTextLabel.font=[UIFont systemFontOfSize:15.0]; 
    cell.detailTextLabel.textColor = [UIColor colorWithRed:(235.0/255.0) green:(120.0/255.0) blue:(33.0/255.0) alpha:1]; 



    return cell; 


} 



-(UITableViewCell *)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 



    NSLog(@"%d", indexPath.row); 


     currentcsvfile = [self.dirList objectAtIndex:indexPath.row ];; 

    csvfilenameSave = [NSString stringWithFormat:currentcsvfile]; 


    NSArray *paths3 = NSSearchPathForDirectoriesInDomains 
    (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory3 = [paths3 objectAtIndex:0]; 

    //make a file name to write the data to using the documents directory: 
    NSString *fileName = [NSString stringWithFormat:@"%@/currentcsvnamefile.txt", 
          documentsDirectory3]; 
    //create content - four lines of text 
    NSString *content =csvfilenameSave; 
    //save content to the documents directory 
    [content writeToFile:fileName 
       atomically:NO 
       encoding:NSStringEncodingConversionAllowLossy error:nil]; 

    [_dirList addObject:_dirList[indexPath.row]]; 


    NSLog(@"\n current csv csvfilenameSave % ",csvfilenameSave); 



//[self performSegueWithIdentifier:@"detailsegue" sender:self]; 

} 

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Update the delete button's title based on how many items are selected. 
    [_dirList removeObject:_dirList[indexPath.row]]; 



} 


-(UITableViewCellEditingStyle)data:(UITableView *)data editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    return UITableViewCellEditingStyleDelete; 
} 


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle== UITableViewCellEditingStyleDelete) { 

     [self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
     [data setEditing:NO animated:YES]; 


     NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 

     NSString *filePath = [docPath stringByAppendingPathComponent:[self.dirList objectAtIndex:indexPath.row ]]; 
     NSError *error = nil; 
     [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; 

     [_dirList removeObjectAtIndex:indexPath.row]; 




    } 
} 

#pragma mark - UITableView Delegate Methods 

//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
//{ 
// return UITableViewCellEditingStyleDelete; 
//} 


#pragma mark - Delete Button Action 


#pragma mark – TableView delegate 

- (void)dealloc { 
    [_timeStamp release]; 

    [self.dirList release]; 
    self.data.delegate = nil; 
    self.data.dataSource = nil; 


    [super dealloc]; 
} 
@end 
+0

显示您的数组列表 - “self.dirList”。将下面这行代码移到方法末尾:'[_dirList removeObjectAtIndex:indexPath.row];' –

+0

成功使用的方法是监视目录中的更改,并在目录中显示文件 - 独立于任何删除/重命名/创建操作。因此,当文件相关操作发生时,一旦文件系统中反映了更改,TableView就会被更新。 –

+0

你为什么要从'didDeselectRowAtIndexPath'中的数组中移除对象? – Lion

回答

0

其实你正在做的是从顶部的数组中删除值。您必须在该函数结束时从数组中删除值。正如我在下面的代码中所做的,请检查我的答案并使用此代码,然后告诉我是否遇到任何问题。我更新我的答案请再检查一次。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
if (editingStyle== UITableViewCellEditingStyleDelete) { 

    currentcsvfile = [self.dirList objectAtIndex:indexPath.row]; 

    csvfilenameSave = [NSString stringWithFormat:currentcsvfile]; 

    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 

    NSString *filePath = [docPath stringByAppendingPathComponent:csvfilenameSave]; 
    NSError *error = nil; 
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; 

    [_dirList removeObjectAtIndex:indexPath.row]; 

    [self.data beginUpdates]; 

    [self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    [self.data endUpdates]; 

    [data setEditing:NO animated:YES]; 

    } 
} 
+0

嗨!只是尝试它,我得到这个错误: 'NSInternalInconsistencyException',原因:'无效的更新:在部分0中的行数无效。更新后(4)的现有部分中包含的行数必须等于(4), – Alivajorg

+0

@Alivajorg,现在你可以试试它,我只是更新它。我赞成我没有在我的答案中加入它。 –

+0

@Alivajorg,你可以添加tableview中的所有tableview代码,如tableview中的行数和段数,如果你使用的是数据源方法 –

0

电话方法[self.data deleteRowsAtIndexPaths:withRowAnimation:];将消息发送到表视图来调整其呈现并因此tableview中引发NSInternalInconsistencyException因为_dirList计数不等于tableviews行计数。

详情看这篇文章Inserting and Deleting Rows and Sections

您可以处理此通过去除对应于 行从第一_dirList阵列项目,然后发送deleteRowsAtIndexPaths:withRowAnimation:表视图。

尝试更换下面的代码行内- (void)tableView:(UITableView *)tableView commitEditingStyle方法:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
if (editingStyle== UITableViewCellEditingStyleDelete) { 

    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]; 

    NSString *filePath = [docPath stringByAppendingPathComponent:[self.dirList objectAtIndex:indexPath.row ]]; 
    NSError *error = nil; 
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; 

    [_dirList removeObjectAtIndex:indexPath.row]; 

    [self.data deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
} 
} 

希望它会工作!

相关问题