views:

3145

answers:

3

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?

Thanks.

+1  A: 

[[[string lastPathComponent] componentsSeparatedByString: @"."] objectAtIndex: 0];

Graham Lee
...gives 'thefile.ext' not 'thefile'.
Anton
This also assumes that the extension is ".", which might be entrenched in time, but stringByDeletingPathExtension is a much better choice.
Jon Hess
+22  A: 

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 .ext from the end.

Peter Nix
OMG! Thank you, thank you, thank you!
Anton
I never heard of `lastPathComponent`. Thank you!
Dimitris
+8  A: 

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
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
Don't forget to check for CFBundleDisplayName first.
Peter Hosey