Skip to content

Instantly share code, notes, and snippets.

@mdippery
Created November 30, 2011 21:27
Show Gist options
  • Save mdippery/1410946 to your computer and use it in GitHub Desktop.
Save mdippery/1410946 to your computer and use it in GitHub Desktop.
Python's os.path.join, for Objective-C
#import <Foundation/Foundation.h>
#import <stdarg.h>
@interface NSString (Paths)
+ (NSString *)stringByJoiningPathComponents:(NSString *)part, ...;
@end
@implementation NSString (Paths)
+ (NSString *)stringByJoiningPathComponents:(NSString *)part, ...
{
NSString *path = [NSString stringWithString:part];
NSString *newPart = nil;
va_list args;
va_start(args, part);
while ((newPart = va_arg(args, NSString *)) != nil) {
path = [newPart isAbsolutePath] ? [NSString stringWithString:newPart] : [path stringByAppendingPathComponent:newPart];
}
va_end(args);
return path;
}
@end
int main(int argc, char **argv)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *path = [NSString stringByJoiningPathComponents:@"/", @"tmp", @"static", @"nybooks.com", nil];
NSLog(@"%@", path);
[pool release];
return 0;
}
@doughnuts64
Copy link

Thanks for this function. I have found it useful in the work I have been doing. I wanted to suggest a possible change to it, though, in order to make it work more like Python's os.path.join. If an absolute path is passed in as one of the subsequent arguments, Python will use that path from then on, discarding anything before. To this end, I would do this:

while ((newPart = va_arg(args, NSString *)) != nil) {
if ([newPart isAbsolutePath])
path = [NSString stringWithString:newPart];
else
path = [path stringByAppendingPathComponent:newPart];
}

I don't know how to insert code into comments...

@mdippery
Copy link
Author

Thanks! I made that modification.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment