dugla
dugla

Reputation: 12954

Cocoa & Cocoa Touch. How do I create an NSData object from a plain ole pointer?

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

Upvotes: 0

Views: 695

Answers (2)

dugla
dugla

Reputation: 12954

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

Upvotes: 0

Barry Wark
Barry Wark

Reputation: 107754

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)

Upvotes: 1

Related Questions