Get filename and extension from filepath programmatically cocoa?

user762034 picture user762034 · Aug 28, 2011 · Viewed 20.5k times · Source

I know you can use NSBundle:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"rtf"];

to get the filepath of a file, but how would I get the filename and extension (separately) from the filepath programmatically using NSBundle.

For example, I may have: /Users/theuser/Documents/yourdocument.txt

It is obvious that the file is 'yourdocument', and the extension 'txt'

But I need to get the filename and extension from the filepath to use as an NSString.

Your help is greatly appreciated!

Answer

chmeee picture chmeee · Aug 28, 2011

There are methods on NSString that do this. Look at -[NSString pathExtension] and -[NSString lastPathComponent], both defined in NSPathUtilities.h.