【问题标题】:How to find all contents with modified date of the directory in Objective C code如何在Objective C代码中查找目录修改日期的所有内容
【发布时间】:2012-12-08 09:51:17
【问题描述】:

此要求非常具体地用于读取目录内容以及所有子文件和文件夹的修改日期。在 Windows 中,我们有一些 API,但我在 Mac OS 开发中没有找到类似的功能。我搜索了这个,发现可以使用 NSFileManager。我找到了一个可以在 Documents 目录下获取路径内容的地方。

这是我拥有的一段代码。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];

NSFileManager *manager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:documentsPath];

for (NSString *filename in fileEnumerator) {
    // Do something with file
    NSLog(@"file name : %@",filename );
}

但我的要求是在机器上的任何路径下找到所有子文件和文件夹修改日期的内容。请指导我。

谢谢, 陶西夫。

【问题讨论】:

    标签: objective-c nsfilemanager


    【解决方案1】:

    Apple 有一个 code sample 演示如何做到这一点:

    NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:directoryPath];
    
    NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:(-60*60*24)];
    
    for (NSString *path in directoryEnumerator) {
    
        if ([[path pathExtension] isEqualToString:@"rtfd"]) {
            // Don't enumerate this directory.
            [directoryEnumerator skipDescendents];
        } else {
            NSDictionary *attributes = [directoryEnumerator fileAttributes];
            NSDate *lastModificationDate = [attributes objectForKey:NSFileModificationDate];
    
            if ([yesterday earlierDate:lastModificationDate] == yesterday) {
                NSLog(@"%@ was modified within the last 24 hours", path);
            }
        }
    }
    

    基本上,此代码枚举directoryPath 并检查文件或目录是否在过去24 小时内被修改。

    【讨论】:

      【解决方案2】:

      您可以为此使用[NSFilemanager.defaultManager subpathsAtPath:<yourpath> error:nil]。请注意,您可能不需要特殊的 NSFileManager 实例,因此您应该使用defaultManager

      NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:(-60*60*24)];
      
      NSFileManager *fm = NSFileManager.defaultManager;
      NSArray *subPaths = [fm subpathsAtPath:documentsPath];
      
      for (NSString *path in subPaths) {
          NSDictionary *attributes = [fm fileAttributesAtPath:path traverseLink:YES];
          NSDate *lastModificationDate = [attributes objectForKey:NSFileModificationDate];
      
          if ([yesterday earlierDate:lastModificationDate] == yesterday) {
              NSLog(@"%@ was modified within the last 24 hours", path);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-04
        • 2015-05-08
        • 2015-08-20
        • 1970-01-01
        • 1970-01-01
        • 2014-12-31
        • 2016-07-03
        • 1970-01-01
        相关资源
        最近更新 更多