36

Is there any way to find the parent directory of a path using NSFileManager or something?

e.g. Take this:

/path/to/something

And turn it into

/path/to/

Binarian
  • 12,296
  • 8
  • 53
  • 84
indragie
  • 18,002
  • 16
  • 95
  • 164

3 Answers3

72

The NSString method -stringByDeletingLastPathComponent does just that.

You can use it like this:

NSLog(@"%@", [@"/tmp/afolder" stringByDeletingLastPathComponent]);

And it will log /tmp.

Binarian
  • 12,296
  • 8
  • 53
  • 84
Jon Hess
  • 14,237
  • 1
  • 47
  • 51
17

Usually file URLs are of type NSURL. There's now a method you can use to grab the parent directory: NSURL *parentDirectory = [fileURL URLByDeletingLastPathComponent];

mikeho
  • 6,790
  • 3
  • 34
  • 46
  • If the URL is for the root of the file system, i.e. `file:///`, then the result of `deletingLastPathComponent()` will be `file:///../`. So, in most cases, you should handle that as a special case. – just_a_guy Jul 14 '21 at 17:33
13

You should use URL for file locations. If you have a path as String I would convert it to URL. For Swift 3 use

let fileURL: URL = URL(fileURLWithPath: "/path/to/something")
let folderURL = fileURL.deletingLastPathComponent()
Binarian
  • 12,296
  • 8
  • 53
  • 84