2012-02-11 48 views
48

我有一個NSMutable字典,它包含fileone.doc或filetwo.pdf的簡單形式中的文件ID及其文件名+擴展名。我需要確定在UITableView中正確顯示相關圖標的文件類型。這是我迄今爲止所做的。獲取包含在NSString中的文件的擴展

NSString *docInfo = [NSString stringWithFormat:@"%d", indexPath.row]; //Determine what cell we are formatting 
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string 

我寫了兩個正則表達式來確定我在看什麼類型的文件,但他們從來沒有返回一個積極的結果。我之前沒有在iOS編程中使用過正則表達式,所以我不完全確定我是否正確地做了這件事,但我基本上從類描述頁面複製了代碼。

NSError *error = NULL; 
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error]; 
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:@"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error]; 
    NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])]; 
    NSLog(@"How many matches were found? %@", numMatch); 

我的問題是,有沒有更簡單的方法來做到這一點?如果不是,我的正則表達式是不正確的?最後,如果我不得不使用它,運行時間是否昂貴?我不知道用戶將有多少文件的平均數量。

謝謝。

回答

143

您正在尋找[fileType pathExtension]

NSString Documentation: pathExtension

+1

呵呵,不知道NSString有'pathExtension'屬性 – remy 2012-02-12 00:02:00

+4

Objective-C只是讓事情變得如此簡單;我不需要想到這種困難的解決方案!謝謝大衛。 – TheJer 2012-02-13 00:40:16

+3

我很高興我沒有嘗試自己做這個功能 – Will 2012-10-12 14:23:09

6
//NSURL *url = [NSURL URLWithString: fileType]; 
NSLog(@"extension: %@", [fileType pathExtension]); 

編輯你可以使用NSString的pathExtension

感謝David巴里

+0

您可以直接在字符串調用pathExtension,無需首先創建一個NSURL。 – 2012-02-12 00:01:15

+3

爲什麼你剛纔撕開了上面的答案,然後記入他? – 2014-03-30 12:52:48

3

嘗試使用[文件pathExtension]到獲取文件的擴展名。

4

試試這個:

NSString *fileName = @"resume.doc"; 
NSString *ext = [fileName pathExtension]; 
0

在斯威夫特3,你可以使用一個擴展:

extension String { 

public func getExtension() -> String? { 

     let ext = (self as NSString).pathExtension 

     if ext.isEmpty { 
      return nil 
     } 

     return ext 
    } 
} 
0

試試這個,它爲我工作。

NSString *fileName = @"yourFileName.pdf"; 
NSString *ext = [fileName pathExtension]; 

文檔這裏NSString pathExtension