Objective-C / cocoa相当于Python的os.path.split()来获取目录名和文件名

当我有一个路径时,我可以在 Python中使用os.path.split()来获取目录名和文件名.

>>> x = '/a/b/c/hello.txt'
>>> import os.path
>>> os.path.split(x)
('/a/b/c', 'hello.txt')

Objective-C / cocoa的等效功能是什么?

有一种更简单的方法(好吧,比乱搞子阵列);查看NSPathUtilities.h.

- (NSString *)lastPathComponent;
- (NSString *)stringByDeletingLastPathComponent;
- (NSString *)stringByAppendingPathComponent:(NSString *)str;

- (NSString *)pathExtension;
- (NSString *)stringByDeletingPathExtension;
- (NSString *)stringByAppendingPathExtension:(NSString *)str;

- (NSArray *)stringsByAppendingPaths:(NSArray *)paths;

使用“/a/b/c/hello.txt”示例:

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'

等等…

相关文章
相关标签/搜索