从部分字符串xcode中删除文件

时间:2015-06-23 02:12:22

标签: ios objective-c iphone xcode string

我正在寻找助手。在我的情况下,我有

等文件
  1. RN150622103444544_pr.pdf
  2. RN150622103444544_ID_GD.pdf
  3. RN150622103444544_CA.xml
  4. 我的问题是如何通过参考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)

您可以将唯一的后缀放在数组中,然后遍历数组。

示例代码(未经测试):

NSArray *suffixList = @[@"pr_1.pdf", @"id_GD.pdf", @"CA.xml"];

NSError *error = nil;
NSFileManager *fm = [NSFileManager defaultManager];

for (NSString *suffix in suffixList) {
    NSString *path = [FormsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%@",proposal, suffix]];
    if([fm fileExistsAtPath:path]){
        [fm removeItemAtPath:path error:&error];
    }
}

注意:问题代码中未使用pathsdocmentsDirectory,但未包含在答案中。