The documentation for URLByDeletingLastPathComponent states the following:
If the receiver’s URL represents the root path, this property contains a copy of the original URL. Otherwise, if the original URL has only one path component, this property contains the empty string.
So maybe this is new in Foundation with the Golden Gate or maybe I just noticed this but the documentation above doesn't seem to be true. This will create an infinite loop:
NSURL *fileURL = [NSURL fileURLWithPath:@"/Users/MyUsername/Desktop/AFolder" isDirectory:YES];
NSLog(@"%@",fileURL);
NSURL *ancestorURL = fileURL.URLByDeletingLastPathComponent;
while (ancestorURL != nil)
{
NSURL *nextAncestor = ancestorURL.URLByDeletingLastPathComponent;
NSLog(@"Next: %@",nextAncestor);
if ([nextAncestor isEqual:ancestorURL])
{
NSLog(@"Hit the root - got a copy of the same url");
break;
}
else if ([nextAncestor.absoluteString isEqualToString:@""]
|| [nextAncestor.path isEqualToString:@""])
{
NSLog(@"Empty string means we had only 1 path component.");
break;
}
else if (nextAncestor == nil)
{
NSLog(@"Got nil");
break;
}
ancestorURL = nextAncestor;
}
The infinite loop can be avoided by adding the following condition:
else if (nextAncestor.pathComponents.count == 1)
{
// One path component.
NSURL *sneakPeak = nextAncestor.URLByDeletingLastPathComponent;
NSLog(@"%lu",sneakPeak.pathComponents.count); // Logs 2.
break;
}
When you get to one path component URLByDeletingLastPathComponent appends a .. path component rather than deleting a path component or returning a copy of the receiver or a url with an empty string..
If this sounds like a bug let me know. When I call URLByDeletingLastPathComponent on a url with only one path component I'd like to get nil. I think that would be a cleaner design.