过滤文档文件夹中的文件

时间:2014-02-16 13:09:45

标签: ios objective-c cocoa-touch

我目前正在使用

在我的文档文件夹中搜索.png图像
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
    fileList=[[NSMutableArray alloc]init];
    for (NSString *filename in dirContents) {
        NSString *fileExt = [filename pathExtension];
        if ([fileExt isEqualToString:@"png"]) {

            [fileList addObject:filename];
        }
    }
    NSLog(@"document folder content list %@ ",fileList);

我想让搜索更具体,例如搜索名为lorry.pngcar.png的图片(为了简洁起见),然后用.png获取所有内容

我的图像文件是通过将参考号self.certificate.reference添加到png来命名的,所以我得到类似car283TYZ.png的内容。这样我就可以为创建它的证书使用正确的图像。

我尝试了什么

//search folder
    NSString *certRefstring = [NSString stringWithFormat:@"%@",self.certificate.reference];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil];
    fileList=[[NSMutableArray alloc]init];
    for (NSString *filename in dirContents) {
        NSString *fileExt = [filename pathExtension];

        if ([fileExt isEqualToString:@"png"]&&[certRefstring rangeOfString:[NSString stringWithFormat:@"%@",self.certificate.reference]].location == NSNotFound) {

            NSLog(@"string does not contain cert ref %@, file list is %@",self.certificate.reference,fileList);


        }
        else{

            NSLog(@"string contains cert ref %@ and png files %@",self.certificate.reference,fileList);

            [fileList addObject:filename];

        }
    }

    NSLog(@"document folder content list %@ ",fileList);

这似乎返回了文件夹中的所有内容。因此,我正在寻找一种解决方案,用于更具体地搜索/迭代我的文档文件夹中的.png文件

2 个答案:

答案 0 :(得分:2)

NSString *certRefstring = [NSString stringWithFormat:@"%@",self.certificate.reference];

所以

[certRefstring rangeOfString:[NSString stringWithFormat:@"%@",self.certificate.reference]].location == NSNotFound

总是没有。你收到一切都是有原因的。 可能应该改为

[filename rangeOfString:[NSString stringWithFormat:@"%@",self.certificate.reference]].location == NSNotFound

答案 1 :(得分:0)

你应该嵌套'if's

if ([fileExt isEqualToString:@"png"])
{
    if ([certRefstring rangeOfString:[NSString stringWithFormat:@"%@",self.certificate.reference]].location == NSNotFound)
    {    
        NSLog(@"string does not contain cert ref %@, file list is %@",self.certificate.reference,fileList);
    }
    else
    {
        NSLog(@"string contains cert ref %@ and png files %@",self.certificate.reference,fileList);
        [fileList addObject:filename];
    }
}