Is it ok to use “classic” malloc()/free() in Objective-C/iPhone apps?

There’s an Objective-C wrapper around raw memory which I like to use a lot for similar tasks: NSMutableData. It has the benefit of giving you retain/release ownership plus it can grow the array easily (without having you to do the realloc yourself).

Your code would look like:

NSMutableData* data = [NSMutableData dataWithLength:sizeof(int) * 100];
int* array = [data mutableBytes];
// memory is already zeroed

// use the array

// decide later that we need more space:
[data setLength:sizeof(int) * 200];
array = [data mutableBytes]; // re-fetch pointer in case memory needed to be copied

// no need to free
// (it's done when the autoreleased object is deallocated)

Leave a Comment