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

When I have the path, I can use os.path.split () in Python to get the directory name and file name.

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

What is the equivalent function in Objective-C / cocoa?

+4
source share
3 answers

There is an easier way (well, than messing with subarrays); take a look at NSPathUtilities.h.

 - (NSString *)lastPathComponent; - (NSString *)stringByDeletingLastPathComponent; - (NSString *)stringByAppendingPathComponent:(NSString *)str; - (NSString *)pathExtension; - (NSString *)stringByDeletingPathExtension; - (NSString *)stringByAppendingPathExtension:(NSString *)str; - (NSArray *)stringsByAppendingPaths:(NSArray *)paths; 

Using the example "/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' 

And so on...

+3
source
 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 
+4
source

NSString has - (NSArray *)pathComponents .

0
source

Source: https://habr.com/ru/post/1341596/


All Articles