How To Create a C Style Array in Objective-C.

Stephen Zaharuk / Thursday, January 7, 2016

So, you've got some data, and you want to store it in an array. Now lets say this data is just a bunch of numbers. In iOS, you could store it in an NSArray, however that requires boxing/unboxing, by wrapping the data in an NSNumber.

But hey, boxing/unboxing is expensive, why would we want to do that? 

Instead, we can create a C style array. 

double array[10];
array[0] = 5.2;

Pretty simple. 

There is another way to declare the same array , however, we take on some responsibility. 

int size = 10;
double* array = calloc(sizeof(double), size);
array[0] = 5.2;

Still simple, however, it's a bit more complicated. Because we allocated space using calloc (we could have just as easily have used malloc), we're responsible for releasing the data. 

free(array);

If we don't free our array when we're done with it, then there will be a memory leak. 

And thats basically it! Hope you found this useful~

By Stephen Zaharuk (SteveZ)