Get the extension of a file contained in an NSString

≯℡__Kan透↙ 提交于 2019-12-28 11:50:11

问题


I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.

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

I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.

    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);

My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.

Thank you.


回答1:


You're looking for [fileType pathExtension]

NSString Documentation: pathExtension




回答2:


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

Edit you can use pathExtension on NSString

Thanks to David Barry




回答3:


Try this :

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



回答4:


Try using [fileType pathExtension] to get the extension of the file.




回答5:


In Swift 3 you could use an extension:

extension String {

public func getExtension() -> String? {

        let ext = (self as NSString).pathExtension

        if ext.isEmpty {
            return nil
        }

        return ext
    }
}



回答6:


Try this, it works for me.

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

Documentation here for NSString pathExtension



来源:https://stackoverflow.com/questions/9245123/get-the-extension-of-a-file-contained-in-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!