4

There are many threads about going the opposite way, but I am interested in converting from a primitive C array to a NSArray. The reason for this is that I want to create a NSString from the array contents. To create the NSString I will use:

NSArray *array;
NSString *stringFromArray = [array componentsJoinedByString:@","];

I am joining the elements of the array by commas because I will later be saving the string as a .csv file. I don't think it matters, but the C array I am dealing with is of type double and size 43.

double c_array = new double [43];

Thanks!

2
  • There's no automatic boxing in ObjC even for primitive types, let alone arrays. So you won't be able to do that without a loop. But if you're coding a loop, you might as well do your string concatenation within that loop - no need to spend time and memory on building a NSArray first. Commented Nov 10, 2011 at 21:47
  • 1
    double c_array = new double[43]; isn't any C array I've ever heard of. Commented Nov 10, 2011 at 22:20

1 Answer 1

6
NSString * stringFromArray = NULL;
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity: 43];
if(array)
{
    NSInteger count = 0;

    while( count++ < 43 )
    {
        [array addObject: [NSString stringWithFormat: @"%f", c_array[count]]];
    }

    stringFromArray = [array componentsJoinedByString:@","];
    [array release];     
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thanks! Only change I made was using a for loop instead of your while loop. The first count value was 1. I needed 0 to access the first element of c_array. Otherwise extremely helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.