3

到目前为止,我已经设法从我的表格视图中删除了行,但它不会在给定的 Documents 文件夹中更新。我将如何实现这一目标?下面是我正在使用的代码。

我试图从这里实现代码How to delete files from a folder which is placed in documents folder

我的目标是能够删除任何文件,而不仅仅是想要的文件。

提前致谢。

#import "Documents.h"

@interface DocumentsViewController ()

@end

@implementation DocumentsViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;


    NSString *temp = [[NSBundle mainBundle] resourcePath];
    self.directoryPath = [temp stringByAppendingPathComponent:@"Documents"];

    [self.tableView setEditing:NO animated:YES];



}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [directoryContents count];
}


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

        static NSString *CellIdentifier = @"Cell";


        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }

        // Configure the cell.
        cell.textLabel.text = [directoryContents objectAtIndex:indexPath.row];

        return cell;
}


-(NSString*)directoryPath{
    return directoryPath;
}

-(void)setDirectoryPath:(NSString*)a{
    [a retain];
    [directoryPath release];
    directoryPath = a;
    [self loadDirectoryContents];
    [table reloadData];
}

-(void)loadDirectoryContents{
    [directoryContents release];
    directoryContents = [[NSFileManager defaultManager] directoryContentsAtPath: directoryPath];
    [directoryContents retain];
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { //implement the delegate method

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Update data source array here, something like [array removeObjectAtIndex:indexPath.row];
        [directoryContents removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [tableView reloadData];


        NSString *extension = @"png";
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
        NSEnumerator *e = [contents objectEnumerator];
        NSString *filename;
        while ((filename = [e nextObject])) {

            if ([[filename pathExtension] isEqualToString:extension]) {

                [fileManager removeItemAtPath:[documentsDirectory     stringByAppendingPathComponent:filename] error:NULL];
            }
        }

    }
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

-(void)dealloc{
    [super dealloc];    
    [directoryContents release];
    directoryContents = nil;
    self.directoryPath = nil;
    [table release];
    table = nil;

}

@end

我的工作代码:

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

        NSString *fileName = [directoryContents objectAtIndex:indexPath.row];

        NSString *path;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"downloads"];
        path = [path stringByAppendingPathComponent:fileName];
        NSError *error;

    //Remove cell
        [directoryContents removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [tableView reloadData];

        if ([[NSFileManager defaultManager] fileExistsAtPath:path])     //Does file exist?
        {
            if (![[NSFileManager defaultManager] removeItemAtPath:path error:&error])   //Delete it
            {
                NSLog(@"Delete file error: %@", error);
            }
        }
    }
}
4

1 回答 1

6

NSFileManager在删除文件时非常有用:

 [[NSFileManager defaultManager] removeItemAtPath: pathToFile error: &error];

也看看这篇文章它有一些有用的代码。虽然有点旧,但代码工作得很好。

http://iphonedevsdk.com/forum/iphone-sdk-development/3576-how-do-i-delete-a-file-in-my-documents-directory.html

这是更多代码示例

// Get the Documents directory path 
NSString *temPath = [NSString stringWithFormat:@"%@%d",@"Documents/Media_",  Key_mediaID];
//This temPath look line ../../../Documents/Media_1

  NSString *documentsDirectoryPath = [NSHomeDirectory()  stringByAppendingPathComponent:temPath]; 

// Delete the file using NSFileManager
 NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[documentsDirectoryPath   stringByAppendingPathComponent:Your File Name] error:nil];

这是另一个链接,其中包含一些更有用的代码

http://ios.biomsoft.com/2012/01/17/delete-all-files-in-documents-directory/

希望这可以帮助你。

编辑:

要删除具有特定扩展名的文件,例如 jpg,您可以尝试以下操作

    NSString *extension = @"jpg";
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];  
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {

    if ([[filename pathExtension] isEqualToString:extension]) {

    [fileManager removeItemAtPath:[documentsDirectory     stringByAppendingPathComponent:filename] error:NULL];
   }
   }

除了上述之外,如果您知道要删除的文件的路径,以下是一个有用的代码:

// Get the Documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES); 
NSString *documentsDirectoryPath = [paths objectAtIndex:0];

// Delete the file using NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[documentsDirectoryPath stringByAppendingPathComponent:yourFile.txt] error:nil];

编辑2:

要删除特定文件夹中的文档:

NSError *error;
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documents= [documentsDirectory  stringByAppendingPathComponent:@"YourFolder"];
NSString *filePath = [documents stringByAppendingPathComponent:@"file2.txt"];
[fileMgr removeItemAtPath:filePath error:&error]
于 2013-06-06T02:29:38.610 回答