2013-02-21 224 views
0

我在应用程序中有一个按钮,点击时应该会打开一个对话框。用户然后选择一个文件夹,单击确定,然后该应用程序显示该文件夹中的PDF文件的数量。查找文件夹中PDF的数量

我下面实现了下面的代码。如何扫描文件夹中的PDF文件数量?

- (IBAction)selectPathButton:(NSButton *)sender { 

    // Loop counter. 
    int i; 

    // Create a File Open Dialog class. 
    NSOpenPanel* openDlg = [NSOpenPanel openPanel]; 

    // Set array of file types 
    NSArray *fileTypesArray; 
    fileTypesArray = [NSArray arrayWithObjects:@"pdf", nil]; 

    // Enable options in the dialog. 
    [openDlg setCanChooseFiles:YES]; 
    [openDlg setAllowedFileTypes:fileTypesArray]; 
    [openDlg setAllowsMultipleSelection:TRUE]; 

    // Display the dialog box. If the OK pressed, 
    // process the files. 
    if ([openDlg runModal] == NSOKButton) { 

     // Gets list of all files selected 
     NSArray *files = [openDlg URLs]; 

     // Loop through the files and process them. 
     for(i = 0; i < [files count]; i++) {    
     } 

     NSInteger payCount = [files count]; 
     self.payStubCountLabel.stringValue = [NSString stringWithFormat:@"%ld", (long)payCount]; 
    } 
} 
+2

到目前为止,您的代码并不完全符合该问题。如果你想让用户选择一个文件夹,然后设置'[openDlg setCanChooseDirectories:YES]'和'[openDlg setCanChooseFiles:NO]'。还是你想让用户多选PDF文件? (因为这是你现在拥有的。) – 2013-02-21 21:55:22

+0

好的。谢谢! – 2013-02-25 16:13:37

+0

我希望用户选择一个文件夹,然后它会计算所选文件夹中的pdf文件数量。上面显示的代码是从另一个论坛帖子复制/粘贴的。 – 2013-02-25 16:23:26

回答

1

获得的文件和目录下的路径

[NSFileManager]- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error; 

获得下路径和子路径的文件和目录

[NSFileManager]- (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error; 

然后过滤掉PDF文件。

NSMutableArray *pdfFiles = [NSMutableArray array]; 
for(NSString *fileName in files) { 
    NSString *fileExt = [fileName pathExtension]; 
    if([fileExt compare:@"pdf" options:NSCaseInsensitiveSearch] == NSOrderSame) { 
     [pdfFiles addObject:fileName]; 
    } 
} 

现在你想要的是pdf文件。

NSUInteger pdfFilesCount = [pdfFiles count]; 

如果您只需要计数pdf文件,只需使用forin循环的变量。

+0

如何在NSFileManager中使用前两行代码? – 2013-02-26 14:27:26

+0

like'[[NSFileManager defaultFileManager] contentsOfDirectoryAtPath:path error:nil];' – YuDenzel 2013-02-27 10:41:01

相关问题