-3

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

    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:来处理数组中的任何文件?我不希望它一次删除所有文件。

4

3 回答 3

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
}
于 2013-01-04T09:25:42.863 回答
1

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

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

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

于 2013-01-04T09:06:56.350 回答
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];
于 2013-01-04T09:09:54.367 回答