Join an Array in Objective-C

Objective CNsmutablearrayNsarray

Objective C Problem Overview


I'm looking for a method of turning a NSMutableArray into a string. Is there anything on a par with this Ruby array method?

>> array1 = [1, 2, 3]
>> array1.join(',')
=> "1,2,3"

Cheers!

Objective C Solutions


Solution 1 - Objective C

NSArray  *array1 = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSString *joinedString = [array1 componentsJoinedByString:@","];

componentsJoinedByString: will join the components in the array by the specified string and return a string representation of the array.

Solution 2 - Objective C

The method you are looking for is componentsJoinedByString.

NSArray  *a = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];//returns a pointer to NSArray
NSString *b = [a componentsJoinedByString:@","];//returns a pointer to NSString
NSLog(@"%@", b); // Will output 1,2,3

Solution 3 - Objective C

NSArray class reference:

NSArray *pathArray = [NSArray arrayWithObjects:@"here",
    @"be", @"dragons", nil];
NSLog(@"%@",
    [pathArray componentsJoinedByString:@" "]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodebeefView Question on Stackoverflow
Solution 1 - Objective CJason CocoView Answer on Stackoverflow
Solution 2 - Objective CRémyView Answer on Stackoverflow
Solution 3 - Objective CGeorg SchöllyView Answer on Stackoverflow