Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rather than continue to defend why I need this, I decided to just write it and share. I based this off of an implementation of Python's <code>os.path.relpath</code> at <a href="http://mail.python.org/pipermail/python-list/2009-August/1215220.html">http://mail.python.org/pipermail/python-list/2009-August/1215220.html</a></p> <pre><code>@implementation NSString (Paths) - (NSString*)stringWithPathRelativeTo:(NSString*)anchorPath { NSArray *pathComponents = [self pathComponents]; NSArray *anchorComponents = [anchorPath pathComponents]; NSInteger componentsInCommon = MIN([pathComponents count], [anchorComponents count]); for (NSInteger i = 0, n = componentsInCommon; i &lt; n; i++) { if (![[pathComponents objectAtIndex:i] isEqualToString:[anchorComponents objectAtIndex:i]]) { componentsInCommon = i; break; } } NSUInteger numberOfParentComponents = [anchorComponents count] - componentsInCommon; NSUInteger numberOfPathComponents = [pathComponents count] - componentsInCommon; NSMutableArray *relativeComponents = [NSMutableArray arrayWithCapacity: numberOfParentComponents + numberOfPathComponents]; for (NSInteger i = 0; i &lt; numberOfParentComponents; i++) { [relativeComponents addObject:@".."]; } [relativeComponents addObjectsFromArray: [pathComponents subarrayWithRange:NSMakeRange(componentsInCommon, numberOfPathComponents)]]; return [NSString pathWithComponents:relativeComponents]; } @end </code></pre> <p>Note that there are some cases this won't correctly handle. It happens to handle all the cases I need. Here is the skimpy unit test I used to verify correctness:</p> <pre><code>@implementation NSStringPathsTests - (void)testRelativePaths { STAssertEqualObjects([@"/a" stringWithPathRelativeTo:@"/"], @"a", @""); STAssertEqualObjects([@"a/b" stringWithPathRelativeTo:@"a"], @"b", @""); STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a"], @"b/c", @""); STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a/b"], @"c", @""); STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a/d"], @"../b/c", @""); STAssertEqualObjects([@"a/b/c" stringWithPathRelativeTo:@"a/d/e"], @"../../b/c", @""); STAssertEqualObjects([@"/a/b/c" stringWithPathRelativeTo:@"/d/e/f"], @"../../../a/b/c", @""); } @end </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload