views:

69

answers:

2

I have malloc'd a whole mess of data in an NSOperation instance. I have a pointer:

data = malloc(humungous_amounts_of_god_knows_what);
uint8_t* data;

How do I package this up as an NSData instance and return it to the main thread? I am assuming that after conversion to an NSData instance I can simply call:

free(data);

Yes?

Also, back on the main thread how do I retrieve the pointer?

Thanks,
Doug

+1  A: 

You want one of the -dataWithBytes:length: or its variants:

NSData *d = [NSData dataWithBytes:data length:lengthOfDataInBytes];

which copies the bytes and you can then free(data). To save a copy, assuming data is allocated using malloc use:

NSData *d = [NSData dataWithBytesNoCopy:data length:lengthOfDataInBytes];

You should not call free on your buffer in this case, as the NSData instance will free it for you.

Note that all of these methods return an autoreleased instance, so you will probably have to retain it if you want to keep it around between threads (and aren't using GC). You can use the equivalent alloc/initWithBytes:... initializers instead.

To get a pointer to an NSData's contents, use bytes.

(I think a few minutes with the NSData documentation will serve you well)

Barry Wark
A: 

Thanks Barry,

I actually went with something even simpler.

Put an NSValue wrapper around the pointer:

NSValue *value = [NSValue valueWithPointer:imageData];

Stuff it in a dictionary to be returned to the main thread:

[result setObject:value forKey:cubicFaceName];

Back on the main thread, when I'm done with the data I discard it:

uint8_t *bits = [value pointerValue];
free(bits);

Cheers,
Doug

dugla