【问题标题】:Is there a way to get folder's creation date in Cocoa?有没有办法在 Cocoa 中获取文件夹创建日期?
【发布时间】:2012-01-17 00:07:57
【问题描述】:

我尝试使用 NSFileManager 的 attributesOfItemAtPath。它适用于文件,但不适用于文件夹。尽管在Apple's documentation 中,他们声称它应该适用于文件或文件夹。但如果我在文件夹上调用它,我得到的只是一个 nil 值。

我使用的代码:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDictionary *folderAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:somePath error:nil];

NSLog(@"Creation date: %@", [dateFormatter stringFromDate:[folderAttributes objectForKey:NSFileCreationDate]]);

输出对我来说总是空的。我的“somePath”是一个 NSString,格式如下:

file://localhost/Users/username/...

想法?谢谢!

【问题讨论】:

    标签: objective-c cocoa nsfilemanager


    【解决方案1】:

    如果是路径,请不要使用 URL。使用路径:

    /用户/用户名/目录

    另外,习惯error参数,真的很有帮助。

    NSError *error = nil;
    NSDictionary *attr = [fm attributesOfItemAtPath:path error:&error];
    if (error)
        NSLog(@"%@", error) /* at least */
    

    它会帮助你。如果由于某种原因您不想要它,请注意参数是指向对象的指针,因此您可能需要使用 NULL 而不是 nil

    【讨论】:

      【解决方案2】:

      somePath 应格式化为直接 POSIX 路径 - 将其设置为 /Users/username/... - 应该可以。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-08
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 2016-08-19
        • 1970-01-01
        相关资源
        最近更新 更多