【问题标题】:select *.jpg file Objective-C选择 *.jpg 文件 Objective-C
【发布时间】:2012-12-20 02:41:40
【问题描述】:

我正在寻找一种在 Objective-C 中选择目录中所有 .jpg 文件的简单方法。现在我只能获取所有目录内容。有没有办法将通配符(如 *.jpg)应用于结果?

 if ( [[NSFileManager defaultManager] isReadableFileAtPath:@"/folder2/"] )
             [[NSFileManager defaultManager] copyItemAtPath:@"/folder2/" toPath:@"/folder1/" error:nil];

【问题讨论】:

    标签: objective-c directory nsfilemanager


    【解决方案1】:

    你可以使用类似的东西:

    NSArray *list = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"/folder2/" error:nil];
    for (NSString* file in list) {
        if ([[file pathExtension] isEqualToString: @"jpg"]) {
             [[NSFileManager defaultManager] copyItemAtPath:file toPath:@"/folder1/" error:nil];
        }
    }
    

    contentsOfDirectoryAtPath:error 方法返回一个包含指定目录中文件名的数组。对于每个条目,将NSString pathExtension 方法的结果与目标字符串(“jpg”)进行比较。任何匹配的文件都会复制到目标目录中。

    【讨论】:

      【解决方案2】:

      几乎直接来自the docs

      NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
      NSString *file;
      while (file = [dirEnum nextObject]) {
          if ([[file pathExtension] isEqualToString: @"jpg"]) {
              // process the document
              [self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
          }
      }
      

      看起来 NSDirectoryEnumerator 也支持快速枚举,所以你可以改用它:

      NSDirectoryEnumerator *dirEnum = [localFileManager enumeratorAtPath:docsDir];
      for (NSString *file in dirEnum) {
          if ([[file pathExtension] isEqualToString: @"doc"]) {
              // process the document
              [self doSomethingWithFile: [docsDir stringByAppendingPathComponent:file]];
          }
      }
      

      使用目录枚举器与遍历-contentsOfDirectoryAtPath: 返回的列表之间的区别在于,目录枚举器还将提供来自子目录的结果。

      【讨论】:

      • 我考虑复制相同的示例。但这会进行深度搜索,这与通配符语义不太匹配。
      猜你喜欢
      • 1970-01-01
      • 2015-08-20
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多