259

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?

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184
Anton
  • 3,352
  • 3
  • 23
  • 15
  • 4
    [path lastPathComponent] or [[path pathComponents] lastObject]. Both gives 'thefile.ext'. There is [path pathExtension] method to get 'ext' but no the same for filename. – Anton Jul 08 '09 at 15:58

3 Answers3

612

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.

Peter
  • 8,545
  • 1
  • 27
  • 24
  • 7
    Another solution would be a combination of this and Marc's answers: `[[[NSFileManager defaultManager] displayNameAtPath:path] stringByDeletingPathExtension]` (use whatever file manager you want). This ensures the filename is correctly localized, and that the extension has been removed. – willurd Jan 09 '11 at 07:55
  • 1
    Thank you so much! This helped a lot! How would you JUST get the extension though? –  Aug 28 '11 at 19:14
  • 21
    @TwoDumpling `NSString *myExtension = [myString pathExtension]` – chown Sep 25 '11 at 02:25
  • Hey, this is quite a bit after this discussion, but I'm just wondering something. How would I reverse this action? I'll eventually add some code to my program to where I can drag and drop a file in. How do I get the PATH ITSELF, so my computer can know which file to access? How do I take the entered file and get the path of the file? – Christian Kreiter May 13 '15 at 23:45
  • Million dollar question & answer.. It also clears the %20 in the URL too.. I didn't used the stringByDeletingPathExtention – Soorej Babu Jan 30 '19 at 08:55
39

If you're displaying a user-readable file name, you do not want to use lastPathComponent. Instead, pass the full path to NSFileManager's displayNameAtPath: method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.

Marc Charbonneau
  • 40,399
  • 3
  • 75
  • 82
  • 1
    For bundles, you may want to use [[[NSBundle bundleWithPath:pref] localizedInfoDictionary] objectForKey:@"CFBundleName"] instead. displayNameAtPath includes the extension where this code returns the localized name. – Peter N Lewis Jul 09 '09 at 05:43
  • 1
    Don't forget to check for CFBundleDisplayName first. – Peter Hosey Jul 09 '09 at 15:03
5

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
Chris Conover
  • 8,889
  • 5
  • 52
  • 68