2013-02-21 228 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

相關問題