【问题标题】:Getting files (and its attributes) in a directory在目录中获取文件(及其属性)
【发布时间】:2011-07-05 14:47:27
【问题描述】:

我想获取目录中的文件列表,但我需要知道该文件是否为目录、上次修改的时间以及它的名称 :) 。所以我尝试了这个:

NSFileManager *fm = [NSFileManager defaultManager];
NSURL *directoryURL = [NSURL fileURLWithPath:@"/Users/nacho4d/Desktop/"];
NSArray *urls = [fm contentsOfDirectoryAtURL:directoryURL 
                      includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, NSURLIsDirectoryKey, NSURLContentModificationDateKey, nil] 
                                         options:NSDirectoryEnumerationSkipsHiddenFiles 
                                           error:nil];
NSError *error = nil;
NSString *name;
NSDate *modificationDate;
NSNumber *isDirectory;
for (NSURL *url in urls) {
    if (![url getResourceValue:&name forKey:NSURLNameKey error:&error]) {
        NSLog(@"name: %@", [error localizedDescription]);error = nil;
    }
    if (![url getResourceValue:&modificationDate forKey:NSURLContentModificationDateKey error:&error]) {
        NSLog(@"modificationDate: %@", [error localizedDescription]); error = nil;
    }
    if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error]) {
        NSLog(@"isDirectory: %@", [error localizedDescription]); error = nil;
    }
    NSLog(@"%@ %@ %@", name, modificationDate, isDirectory);
}

但是我总是得到(null) (null) (null),没有错误但没有数据;(

我想知道这里有什么问题?

PS:我知道contentsOfDirectoryAtPath:error:attributesOfItemAtPath:error: 但我认为这不是最好的方法,是吗? 我计划在可以包含大量文件的文件夹中使用它,所以我想尽可能以最有效的方式执行此操作。

为 iOS5 及更高版本编辑

正如@jeremyP 所指出的,According to the docs 该方法在 iOS4 中未实现,但从 iOS5 及更高版本开始,它似乎可以正常工作:

可用性
在 iOS 5.0 及更高版本中可用。 (iOS 4 中存在符号,但不执行任何操作。)

这个问题是在我认为是最新的 iOS4 时完成的。现在在 iOS 5 和 6 一切都按预期工作:)

【问题讨论】:

  • 这是 iOS 还是 Mac OS 问题?请注意,根据 Apple 文档,此方法未在 iOS 中实现。
  • 我正在尝试在 iPhone 中执行此操作。请参阅杰里米回答的第四条评论
  • iOS 问题请使用 cocoa-touch 标签。 cocoa 标签适用于 Mac OS X 上的 Cocoa。

标签: iphone objective-c cocoa-touch


【解决方案1】:

这不是您问题的答案,但您的错误检查应如下所示:

if (![url getResourceValue:&name forKey:NSURLNameKey error:&error])
{
    NSLog(@"name: %@", [error localizedDescription]);error = nil;
}

编辑

无法弄清楚问题出在哪里,但刚刚重读了the documentation on the method。重要的句子是正在讨论的那句话:

此方法在iOS中未实现,因此不执行任何操作。

【讨论】:

  • 我刚刚更新了代码 :) 任何想法为什么这不起作用?
  • 我真的看不出代码有什么问题。您可以尝试记录 NSURL 以及资源值吗?
  • 哦!!...我明白了。但是,如果 getResourceValue:forKey:error: 未实现,那么如何获取在 contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: 方法中预取的文件属性?我真的需要使用attributesOfItemAtPath:error 吗?
  • 是的,您应该这样做,并且使用 NSDictionary “文件管理器”方法轻松检索返回的字典值。
  • 只是从文档中添加一些重要信息:Available in iOS 5.0 and later. (Symbol is present in iOS 4, but performs no operation.) 这个问题是在我认为最新的 iOS4 时完成的。现在在 iOS 5 和 6 中一切都按预期工作:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-16
相关资源
最近更新 更多