Sunday, May 19, 2013

NSString pathComponents example ios

[NSString pathComponents]

Returns an array of NSString objects containing, in order, each path component of the receiver.
- (NSArray *)pathComponents
Return Value
An array of NSString objects containing, in order, each path component of the receiver.
Discussion of [NSString pathComponents]
The strings in the array appear in the order they did in the receiver. If the string begins or ends with the path separator, then the first or last component, respectively, will contain the separator. Empty components (caused by consecutive path separators) are deleted. 
Example of [NSString pathComponents]
NSString* filePath = // something

NSArray* pathComponents = [filePath pathComponents];

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

Example of [NSString pathComponents]
- (NSString *)mergeStringsPrefix:(NSString *)prefix suffix:(NSString *)suffix
    NSString *string = [NSString stringWithFormat:@"%@", prefix];

    NSArray *prefixComponents = [prefix pathComponents];
    NSArray *suffixComponents = [suffix pathComponents];

    if ([prefixComponents count] == 0) return [string retain]; 
    int rootIndex = [suffixComponents indexOfObject:@"/"];
    int index = 1;
    if (rootIndex == NSNotFound || rootIndex != 0) index = 0;

    int startIndex = [prefixComponents indexOfObject:[suffixComponents objectAtIndex:index]];
    if (startIndex == NSNotFound) return nil;

    if ([suffixComponents count] - index < [prefixComponents count] - startIndex) return nil;

    // fing length and check merge compatability
    BOOL equalParts = YES;
    for (int i=startIndex; i<[prefixComponents count] && equalParts; i++, index++)
        NSString *el1 = [prefixComponents objectAtIndex:i];
        NSString *el2 = [suffixComponents objectAtIndex:index];

        if ([el1 compare:el2] != NSOrderedSame) equalParts = NO;
    if (!equalParts) return nil;
    // merge
    for (int i=index; i<[suffixComponents count]; i++)
        string = [string stringByAppendingFormat:@"/%@", [suffixComponents objectAtIndex:i]];

    return [string retain];
Example of [NSString pathComponents]
NSURL* url = [NSURL URLWithString:@""];
NSString* reducedUrl = [NSString stringWithFormat:
    [url.pathComponents objectAtIndex:1]];