How to convert dispatch_data_t to NSData?

hfossli picture hfossli · Feb 5, 2012 · Viewed 8.1k times · Source

Is this the right way?

// convert
const void *buffer = NULL;
size_t size = 0;
dispatch_data_t new_data_file = dispatch_data_create_map(data, &buffer, &size);
if(new_data_file){ /* to avoid warning really - since dispatch_data_create_map demands we care about the return arg */}

NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];

// use the nsdata... code removed for general purpose

// clean up
[nsdata release];
free(buffer); // warning: passing const void * to parameter of type void *

It is working fine. My main concern is memory leaks. Leaking data buffers is not fun. So is the NSData, the buffer and the dispatch_data_t new_data_file all fine?

From what I can read on http://opensource.apple.com/source/libdispatch/libdispatch-187.7/dispatch/data.c it seems the buffer is DISPATCH_DATA_DESTRUCTOR_FREE. Does that mean it is my responsibility to free the buffer?

Answer

catlan picture catlan · Oct 29, 2013

Since iOS 7 and macOS 10.9 (Foundation Release Notes) dispatch_data_t is an NSObject (NSObject <OS_dispatch_data>) in 64 bit apps.

dispatch_data_t can now be freely cast to NSData *, though not vice versa.