Friday, May 31, 2013

NSArray componentsJoinedByString example in Objective C (iOS).


NSArray componentsJoinedByString


Constructs and returns an NSString object that is the result of interposing a given separator between the elements of the array.

- (NSString *)componentsJoinedByString:(NSString *)separator

Parameters
separator
The string to interpose between the elements of the array.

Return Value
An NSString object that is the result of interposing separator between the elements of the array. If the array has no elements, returns an NSString object representing an empty string.

Discussion of [NSArray componentsJoinedByString]
For example, this code excerpt writes "here be dragons" to the console:

NSArray *pathArray = [NSArray arrayWithObjects:@"here", @"be", @"dragons", nil];
NSLog(@"%@",[pathArray componentsJoinedByString:@" "]);
Special Considerations
Each element in the array must handle description.

NSArray componentsJoinedByString example.
NSArray  a = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSString b = [a componentsJoinedByString:@","];
NSLog(b); // Will output 1,2,3

Example of [NSArray componentsJoinedByString].
string = [string stringByAppendingString:[food componentsJoinedByString:@", "]];
is the same as

NSString *tmpString = [food componentsJoinedByString:@", "];
string = [string stringByAppendingString:tmpString];

NSArray componentsJoinedByString example.
- (NSMutableArray *) getArrayOfCommaSeparatedSelectorStrings
{
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSMutableArray *e in [self getArrayOfSelectorArrays])
        [array addObject:[e componentsJoinedByString:@", "]];

    return array;
}

End of NSArray componentsJoinedByString example article.