views:

2979

answers:

2

Hello, I am wondering how to convert an NSArray example: ( [43,545,@"Test"] ) to a string in objective-c. An applescript example might be:

set the_array to {43,"Testing", 474343}
set the_array to the_array as string
+6  A: 

One approach would be to iterate over the array, calling the description message on each item:

NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
    [result appendString:[obj description]];
}
NSLog(@"The concatenated string is %@", result);

Another approach would be to do something based on each item's class:

NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
    if ([obj isKindOfClass:[NSNumber class]])
    {
        // append something
    }
    else
    {
        [result appendString:[obj description]];
    }
}
NSLog(@"The concatenated string is %@", result);

If you want commas and other extraneous information, you can just do:

NSString * result = [array description];
Jason
If the array has many elements it might be more efficient to first convert all elements to strings (probably using `-description`) and concat them after that using `-componentsJoinedByString:` with `@""` as the parameter.
Georg
I would go with this method over the one by Dave Delong unless your just debugging.
TechZen
+10  A: 

This does what Jason has, but it's simpler:

NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];
Dave DeLong
Won't this accomplish the same thing as calling [array description]?
TechZen
@TechZen - no, because `[array description]` inserts newlines and the outer parentheses.
Dave DeLong