如何使用NSPredicate从部分字符串创建文件名然后删除文件?

时间:2015-06-29 08:56:34

标签: ios objective-c nspredicate

我有以下文件:

  

RN150622103444544_pr.pdf
     RN150622103444544_ID_GD.pdf
     RN150622103444544_CA.xml

我的问题是如何通过使用NSPredicate 引用 RN150622103444544 部分名称来删除所有文件。

目前我的代码正逐一删除:

-(void)deleteOldPdfs:(NSString *)proposal
{

    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_pr_1.pdf",proposal]]])
       [fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_pr_1.pdf",proposal]] error:&error];

    if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_id_GD.pdf", proposal]]])
       [fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_id_GD.pdf", proposal]] error:&error];

    if([fm fileExistsAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_CA.xml", proposal]]])
       [fm removeItemAtPath:[FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_CA.xml",proposal]] error:&error];

}

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容列出目录的内容,然后使用NSPredicate将这些内容过滤到仅包含您标签的路径。

- (void) deleteFilesContainingLabel:(NSString *)label{        
    NSFileManager *fm = [NSFileManager defaultManager];

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

    // Create a predicate to filter out file paths containing the required
    // label.
    NSPredicate *filter = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"self CONTAINS '%@'",label]];

    // List the directory
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:documentsDirectory error:nil];

    // Filter the list using our predicate
    NSArray *filteredFiles = [dirContents filteredArrayUsingPredicate:filter];

    // Delete the files which pass the predicate filter.
    NSError *error;
    for (NSString *path in filteredFiles){
      [fm removeItemAtPath:path error:&error];
    }
}