Working with NSString & POSIX paths

In dealing with publishing to a server, Sandvox works with paths a lot. Helpfully, NSString provides a pretty rich set of methods for manipulating paths. Recently though, we had a bit of a nasty bug with the nature of POSIX paths. Under the POSIX standard, a trailing slash in a pathname is insignificant. For the majority of Cocoa this doesn't matter to you, the frameworks happily accept paths with and without trailing slashes, but if you're comparing two paths you can trip up quite easily. This is exactly what happened in Sandvox, we were effectively doing this and expecting it to return YES:

[@"/foo" isEqualToString:@"/foo/"]

No surprises that it didn't work! It was pretty easy to patch up, and since I couldn't find any equivalent open source code out in the world, here it is for others to benefit from and enjoy:

- (NSString *)standardizedPOSIXPath
											{
											    if ([self length] > 1 && [self hasSuffix:@"/"]) // Stops @"/" being altered
											    {
											        return [self substringToIndex:([self length] - 1)];
											    }
											    else
											    {
											        return self;
											    }
											}
											
											- (BOOL)isEqualToPOSIXPath:(NSString *)otherPath
											{
											    BOOL result = [[self standardizedPOSIXPath] isEqualToString:
											        [otherPath standardizedPOSIXPath]];
											    return result;
											}

Strictly speaking, the second method isn't all that useful, but if it ever becomes a concern, one could optimise it to not use autoreleased strings. Give us a shout in the comments if you make any interesting changes or spot any bugs.

© Mike Abdullah 2007-2015