【问题标题】:How to get list of contents from folder using contentsOfDirectoryAtPath in cocoa?如何使用可可中的 contentsOfDirectoryAtPath 从文件夹中获取内容列表?
【发布时间】:2018-01-25 10:58:21
【问题描述】:

我想获取文件夹的所有内容并添加到 NSMenuItems 的子菜单中。

为了实现这一点,我使用下面给出的代码:

NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:nil];

此代码有效,但仅在一个文件夹中。奇怪但这是真的。我已经为其他文件夹尝试了相同的代码,但它在dirContents 中给出了 nil 值。

那么如何访问所选文件夹的所有内容列表呢?

【问题讨论】:

  • 请考虑在沙盒应用程序中,对容器外部文件夹的访问受到限制。并且强烈推荐使用NSFileManagerURL相关API

标签: objective-c cocoa nsfilemanager


【解决方案1】:

试试这个来跟踪访问错误。

NSError *error;
NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:&error];

if(error){
    NSLog(@"%@",error);
}

确保使用目录的相对路径(如果应用是沙盒),而不是绝对路径。

NSURL *containerUrl =[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"Your.app.container.id"];
path = [[containerUrl URLByAppendingPathComponent:@"your/folder/path"] path];

【讨论】:

    【解决方案2】:
    +(NSArray*)allURLs:(NSURL*)url{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
        NSURL *bundleURL = url;
        NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
                                              includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                                 options:NSDirectoryEnumerationSkipsHiddenFiles
                                                            errorHandler:^BOOL(NSURL *url, NSError *error)
                                             {
                                                 NSLog(@"[Error] %@ (%@)", error, url);
                                                 return url;
                                             }];
    
        NSMutableArray *mutableFileURLs = [NSMutableArray array];
        for (NSURL *fileURL in enumerator) {
            NSString *filename;
            [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
    
            NSNumber *isDirectory;
            [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
    
            // Skip directories with '_' prefix, for example
            if ([filename hasPrefix:@"_"] && [isDirectory boolValue]) {
                [enumerator skipDescendants];
                continue;
            }
    
            if (![isDirectory boolValue]) {
                [mutableFileURLs addObject:fileURL];
            }
        }
    
    
        return mutableFileURLs;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多