Getting the last 2 directories of a file path Getting the last 2 directories of a file path objective-c objective-c

Getting the last 2 directories of a file path


NSString has loads of path handling methods which it would be a shame not to use...

NSString* filePath = // somethingNSArray* pathComponents = [filePath pathComponents];if ([pathComponents count] > 2) {   NSArray* lastTwoArray = [pathComponents subarrayWithRange:NSMakeRange([pathComponents count]-2,2)];   NSString* lastTwoPath = [NSString pathWithComponents:lastTwoArray];}


I've written function special for you:

- (NSString *)directoryAndFilePath:(NSString *)fullPath{    NSString *path = @"";    NSLog(@"%@", fullPath);    NSRange range = [fullPath rangeOfString:@"/" options:NSBackwardsSearch];    if (range.location == NSNotFound) return fullPath;    range = NSMakeRange(0, range.location);    NSRange secondRange = [fullPath rangeOfString:@"/" options:NSBackwardsSearch range:range];    if (secondRange.location == NSNotFound) return fullPath;    secondRange = NSMakeRange(secondRange.location, [fullPath length] - secondRange.location);    path = [fullPath substringWithRange:secondRange];    return path;}

Just call:

[self directoryAndFilePath:@"/Users/Documents/New York/SoHo/abc.doc"];


  1. Divide the string into components by sending it a pathComponents message.
  2. Remove all but the last two objects from the resulting array.
  3. Join the two path components together into a single string with +pathWithComponents: