Objective-C: Extract filename from path string

Anton picture Anton · Jul 8, 2009 · Viewed 113.9k times · Source

When I have NSString with /Users/user/Projects/thefile.ext I want to extract thefile with Objective-C methods.

What is the easiest way to do that?

Answer

Peter picture Peter · Jul 8, 2009

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.