问题
When I have a path, I can use os.path.split() in Python to get directory name, and file name.
>>> x = '/a/b/c/hello.txt'
>>> import os.path
>>> os.path.split(x)
('/a/b/c', 'hello.txt')
What's the equivalent function in Objective-C/cocoa?
回答1:
There is an easier way (well, than messing with subarrays); look in NSPathUtilities.h.
- (NSString *)lastPathComponent;
- (NSString *)stringByDeletingLastPathComponent;
- (NSString *)stringByAppendingPathComponent:(NSString *)str;
- (NSString *)pathExtension;
- (NSString *)stringByDeletingPathExtension;
- (NSString *)stringByAppendingPathExtension:(NSString *)str;
- (NSArray *)stringsByAppendingPaths:(NSArray *)paths;
Using the "/a/b/c/hello.txt" example:
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'
And so on...
回答2:
NSString *a = @"/a/b/c/hello.txt";
NSArray *path = [a pathComponents];
NSArray *startOfPath = [path subarrayWithRange:NSMakeRange(0, [path count]-2)];
[NSString pathWithComponents:startOfPath]; // /a/b/c
[a lastPathComponent]; // hello.txt
回答3:
NSString has - (NSArray *)pathComponents.
来源:https://stackoverflow.com/questions/5138677/objective-c-cocoas-equivalent-to-pythons-os-path-split-to-get-directory-name