Objective-C: Extract filename from path string

Objective CCocoa

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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.

Solution 2 - Objective C

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.

Solution 3 - Objective C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAntonView Question on Stackoverflow
Solution 1 - Objective CPeterView Answer on Stackoverflow
Solution 2 - Objective CMarc CharbonneauView Answer on Stackoverflow
Solution 3 - Objective CChris ConoverView Answer on Stackoverflow