0Day Forums
Objective-C: Extract filename from path string - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: Objective-C (https://0day.red/Forum-Objective-C)
+--- Thread: Objective-C: Extract filename from path string (/Thread-Objective-C-Extract-filename-from-path-string)



Objective-C: Extract filename from path string - antequalm651838 - 07-21-2023

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?


RE: Objective-C: Extract filename from path string - terryedvnkka - 07-21-2023

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.


RE: Objective-C: Extract filename from path string - mon161 - 07-21-2023

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



RE: Objective-C: Extract filename from path string - Propagans885 - 07-21-2023

Taken from [the NSString reference][1], 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.


[1]:

[To see links please register here]