boyfarrell.com

7 November 2007

Garbage collected buffers

Since the original post I realised there is a problem with the approach (thanks to Rick Hog). The garbage collector only collects objects! As such you must not dereference the pointer to the NSMutableData, you must assign it, and, on another line, make the method call to mutableBytes.

Now that Cocoa as garbage collection there if a real advantage to using it to allocate buffer. Where before I would have just made a quick malloc statement to get some dynamic memory:
// buffer/dynamic array that holds with 10 doubles
double *x;
x = (double*) malloc(sizeof(double) * 10);
//... sometime later ...
free(x);

Now I find myself doing,
double *x = [[NSMutableData dataWithCapacity:sizeof(double) * 10] mutableBytes];
NSMutableData *buffer = [NSMutableData dataWithCapacity:sizeof(double) * 10];
double *x = [buffer mutableBytes];

Garbage collected buffers; for the lazy at heart.

No Comments currently posted.

Post a comment on this entry: