2010-05-14 97 views
1

我正在尝试统计目录中的整个文件,包括子目录。这是我的第一个文件夹来算的文件:计算目录和子目录中的文件? iPhone

-(NSString *)numberOfPhotos 
{ 
    NSString *MyPath = @"/rootdirectory/"; 
    NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath:MyPath]; 

    return [NSString stringWithFormat:@"%d", [directoryContent count]]; 
} 

我想也许像

for (file in folder){ 
    [file count] 
{ 

的东西,但似乎没有工作。

UPDATE: 其实很简单:

NSDirectoryEnumerator *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:musicPath error:nil]; 

回答

5
NSDirectoryEnumerator *subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:musicPath error:nil]; 
+0

它将返回一个NSArray对象而不是NSDirectoryEnumerator – dark 2012-06-19 08:18:04

+0

NSArray * subs = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath: musicPath错误:无]; – BhushanVU 2014-03-25 12:17:58

3

你在正确的轨道上。你需要一个递归方法。您传递一个目录,该方法获取目录中的所有文件,然后检查每个目录是否为目录。在这里你需要一个for循环来检查当前对象是否是一个目录。如果它是一个目录,那么它会自动调用目录名称。如果没有,它会增加一个计数器并继续。

现在无法发布代码,但这就是您要这样做的方式。

+0

PLZ帖子的时候就可以了! – WrightsCS 2010-05-15 00:32:35

+0

我发布了一些伪代码,以便您可以在另一个答案中看到递归算法。 – progrmr 2010-05-15 16:59:28

+0

+1,挑剔的角落:你并不需要确定递归算法来遍历一棵树,但当然更容易;-) – 2010-05-15 17:03:13

1

看能不能使用iPad键盘编写代码...使用伪代码来描述递归算法:

int fileCount(directory) 
{ 
    int count = 0; 
    for (file in directory) 
    { 
     if (isDirectory(file)) 
      count += fileCount(file); 
     else 
      count++; 
    } 
    return count; 
}     
相关问题