[NSString stringByDeletingLastPathComponent]
Returns a new string made by deleting the last path component from the receiver, along with any final path separator.
- (NSString *)stringByDeletingLastPathComponent
Return Value
A new string made by deleting the last path component from the receiver, along with any final path separator. If the receiver represents the root path it is returned unaltered.
Discussion of [NSString stringByDeletingLastPathComponent]
The following table illustrates the effect of this method on a variety of different paths:
Receiver’s String Value
|
Resulting String
|
---|---|
“/tmp/scratch.tiff ” | “/tmp ” |
“/tmp/lock/ ” | “/tmp ” |
“/tmp/ ” | “/ ” |
“/tmp ” | “/ ” |
“/ ” | “/ ” |
“scratch.tiff ” | “” (an empty string) |
Note that this method only works with file paths (not, for example, string representations of URLs).
Example of [NSString stringByDeletingLastPathComponent]
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSString *secondParentPath = [[bundlePath stringByDeletingLastPathComponent] stringByDeletingLastPathComponent];
Example of [NSString stringByDeletingLastPathComponent]
NSString *path = @"/a/b/c/hello.txt";
NSString *fileName = [path lastPathComponent];
// 'hello.txt'
NSString *basePath = [path stringByDeletingLastPathComponent];
// '/a/b/c'
NSString *newPath = [basePath stringByAppendingPathComponent:@"goodbye.txt"];
// '/a/b/c/goodbye.txt'
Example of [NSString stringByDeletingLastPathComponent]
NSString *source = @"/FILE.txt";
NSString *newName = [[source lastPathComponent] lowercaseString];
NSString *temp = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-temp", newName]];
NSString *target = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];
[[NSFileManager defaultManager] movePath:source toPath:temp error:nil];
[[NSFileManager defaultManager] movePath:temp toPath:target error:nil];
Example of [NSString stringByDeletingLastPathComponent]
NSString *oldPath = @"/Users/brock/Desktop/OriginalFile.png";
NSString *newFilename = @"NewFileName.png";
NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];
NSLog( @"File renamed to %@", newFilename );