Objective-C/cocoa's equivalent to Python's os.path.split() to get directory name and file name

江枫思渺然 提交于 2019-12-12 12:25:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!