The "non-optimized" statement is only valid for the code that you have. Apple frameworks are very optimized, and you should not assume that Apple guessed, they already guessed that you already guessed.
First use the methods to create them. The way to create an unsorted array simply erases the memory. In each individual step of the loop, you create a new instance of the array, in the end, you get 256 (or something like an array of the original array) arrays, which is just superfluous.
So, if you really, badly want to use Objective-C to solve this problem, you can use a mutable array, and you only need one NSMutableArray :
int array[256];
By the way, even two loops (one for filling the C array and one for converting to NSMutableArray ) are not needed here. You can just write
const size_t size = 256; NSMutableArray *objcArray = [NSMutableArray array]; for (int i = 0; i < size; i++) { [objcArray addObject:[NSNumber numberWithInt:arc4random_uniform(256)]; } [objcArray sortUsingSelector:@selector(compare:)];
However, you do not need Objective-C to sort an integer array. You can simply write a C function (or, if you want, an Objective-C method) to sort the integer array in place, and this can be somewhat more efficient or faster:
#include <math.h> #include <stdlib.h> #include <unistd.h> int compare(const void *first, const void *second) { return *(const int *)first - *(const int *)second; } - (void)sortArray:(int *)array ofSize:(size_t)sz { qsort(array, sz, sizeof(*array), compare); }
Then use it as follows:
int array[256]; for (int i = 0; i < sizeof(array) / sizeof(*array); i++) { array[i] = arc4random_uniform(256); } [self sortArray:array ofSize:sizeof(array) / sizeof(*array)];
Also, read this about arrays . Really nice article.