2017-10-17 83 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]; 
} 
} 

希望它會工作!

相關問題