Take the 2-minute tour ×

I have code like this:

NSData *data = [NSData dataWithContentsOfURL:objURL];
const void *buffer = [data bytes];
[self _loadData:buffer];
[data release];

the "_loadData" function takes an argument like:

- (void)_loadData:(const char *)data;

How do I convert "const void " to a "const char" on Objective-C?

share|improve this question
The [data release]; line is unnecessary. On non-garbage-collected environments your application will likely crash and it shows that you do not fully understand Cocoa memory management. You only release if you have explicitly called alloc, copy, or mutableCopy (maybe others that I can't think of right now). The object returned from [NSData dataWithContentsOfURL:] is automatically released or garbage collected. –  dreamlax Apr 19 '09 at 17:00
Even on the iPhone where there is no garbage collection? –  Nick VanderPyle Apr 19 '09 at 17:10
In a non-garbage collected environment the object is added to an autorelease pool and will likely be deallocated in the next event loop or when the pool itself is deallocated. In any case, you do not "own" the returned object so it is not yours to release, if you know what I mean. You only own objects that you explicitly allocate, through either +alloc, -copy, or -mutableCopy (and maybe others). –  dreamlax Apr 19 '09 at 17:27
Ahh. I understand. Thank you. :) I have some more reading to do on the subject, but your explanation has definitely helped. Basically, don't worry about releasing the object unless I explicitly allocated or copied it. –  Nick VanderPyle Apr 19 '09 at 17:37

2 Answers 2

up vote 5 down vote accepted

Just like you would in C:

[self _loadData:(const char *)buffer];

should work.

share|improve this answer
Thanks! I had tried assigning buffer to another type thinking "they're just pointers, it should work." const char *charBuff = buffer; Never thought to cast it. Ha! –  Nick VanderPyle Apr 19 '09 at 17:09
That would have worked too actually, except "const char *charBuff = (const char *)buffer; (assigning to a char * variable, you still need the cast) –  duncanwilcox Apr 19 '09 at 21:56

You mustn't release the data object because you did not explicitly allocate it. Also, you could do a simple cast:

[self _loadData:(const char *) buffer];
share|improve this answer
Good catch on the NSData. I need to read more about memory management. Thanks! –  Nick VanderPyle Apr 19 '09 at 16:57

Your Answer


