【问题标题】:How to filter array and let stay only strings end with .png如何过滤数组并只保留以.png结尾的字符串
【发布时间】:2015-03-03 23:50:29
【问题描述】:

我正在从文件夹中读取文件,文件夹包含.pngs,但我在每个文件夹中都获得了额外的Thumb.db 文件,其他所有文件都是.png。我将内容阅读为

NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];

如何删除数组中包含.db 的所有文件或保留以.png 结尾的文件?

【问题讨论】:

标签: ios objective-c ios7 ios8 nsfilemanager


【解决方案1】:

我认为通过使用 NSPredicate 方法可以得到准确的值

NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
NSString *str              = @".png"
NSPredicate *sPredicate    = [NSPredicate predicateWithFormat:@"SELF contains[c] %@",str];
NSArray *predicateArray    = [directoryContent filteredArrayUsingPredicate:sPredicate];

【讨论】:

    【解决方案2】:

    在 Cocoa 中过滤数组的惯用方式是 NSPredicate:

    NSArray *filtered = [directoryContent filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension = png"]];
    

    谓词中提到的pathExtension 方法是NSString 上的一个方法,它试图将字符串解释为文件系统路径,并返回扩展名。

    【讨论】:

      【解决方案3】:

      试试这个代码:

          NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
          NSMutableArray *imageArray = [[NSMutableArray alloc] init];
      
          for (NSString *path in directoryContent) 
          {
             if ([path hasSuffix:@".png"]) 
             {
                [imageArray addObject: path];
             }
          }
      
          NSLog (@"Number of images : %d" , [imageArray count]);
      

      【讨论】:

      • NSPredicate 是一个更简单的解决方案
      • 是的,即使我之前不知道。
      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      • 1970-01-01
      • 2022-08-15
      • 2020-09-24
      相关资源
      最近更新 更多