ios - 删除文档目录中的任何文件,但不是所有文件

时间:2013-01-04 09:01:58

标签: objective-c ios nsfilemanager nsdocumentdirectory

我有这段代码,它允许我指定要从我的文档目录中删除的特定文件。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];

    NSString* checkIfFileExists = [documentsDirectoryPath stringByAppendingPathComponent:_fileName];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager removeItemAtPath:checkIfFileExists error:NULL];

如果您想删除带有按钮的文件,我可以看到这很有用,但是如何引用removeItemAtPath:来处理数组中的任何文件,而不是只想删除特定文件?我不希望它一次删除所有文件。

3 个答案:

答案 0 :(得分:1)

您可以获取- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error NSFileManager的目录内容。

https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html

然后遍历数组并逐个删除文件。

答案 1 :(得分:1)

您可以使用相同的代码。

但需要添加文件名,如:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];
NSString *file = [documentsDirectoryPath stringByAppendingString:@"%@",[yourFileNamesArray objectAtIndex:0];

NSString* checkIfFileExists = [file stringByAppendingPathComponent:_fileName];

NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:checkIfFileExists error:NULL];

答案 2 :(得分:1)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [[paths objectAtIndex:0] stringByAppendingString:@"/Podcasts"];
NSString* checkIfFileExists = [documentsDirectoryPath stringByAppendingPathComponent:_fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isMyFileThere = [[NSFileManager defaultManager] fileExistsAtPath:checkIfFileExists];
if(isMyFileThere){

          [fileManager removeItemAtPath:checkIfFileExists error:NULL];
}
else{
          //file dont exists
}