UITableView - 删除单元格时如何删除文件?

时间:2017-10-17 04:20:49

标签: ios objective-c uitableview

我正在尝试删除单元格时删除csv文件,但是当我按下删除时,我收到了下一个错误:

  

由于未捕获的异常'NSRangeException'终止应用程序,原因:' * - [__ NSArrayM objectAtIndex:]:索引3超出边界[0 ..   2]”   * 首先抛出调用堆栈:

代码:

//

/

/  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

2 个答案:

答案 0 :(得分: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];

    }
}

答案 1 :(得分: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];
}
}

希望它能奏效!