PDA

View Full Version : How return NSData object from a method?




ssawgift
Mar 28, 2012, 09:58 PM
I have ARC on for my test project, and one of my class has this method:


- (int) GetData: (NSData**)data
{
uint8_t * p = malloc(10);
for (int i = 0; i < 10; i++) {
p[i] = i + 1;
}
*data = [NSData dataWithBytesNoCopy: p length:10 freeWhenDone:YES];
}


Here is what I do to call this method:

NSData * data = nil;
[theObject GetData:&data];


But data always is nil after the call.

If I turn off ARC for the projec then it works as expected. I want to have ARC on while having this method work. What should I do?

PS: Is this a serious bug? I think when I do *data = ... the object apparently has a reference and should not be released when the method exits.



mfram
Mar 29, 2012, 01:30 AM
Why not just make the method:


- NSData *GetData
{
uint8_t * p = malloc(10);

for (int i = 0; i < 10; i++) {
p[i] = i + 1;
}

return [NSData dataWithBytesNoCopy: p length:10 freeWhenDone:YES];
}


Not sure if it will help.

Catfish_Man
Mar 29, 2012, 01:01 PM
That change will help, but, in order to be truly correct needs to have the method renamed as well. "get" implies return via argument; returning it directly would just be - (NSData *) data;

gnasher729
Mar 29, 2012, 04:22 PM
I have ARC on for my test project, and one of my class has this method:
If I turn off ARC for the projec then it works as expected. I want to have ARC on while having this method work. What should I do?

What you should do is read the ARC documentation. Carefully. I'd look at the declaration of one of the many methods having an NSError** parameter. ARC does things for you, but you still need to understand how memory management works.

And why on earth are you declaring a method as returning an int when you don't return a value? And why don't you turn on some compiler warnings to prevent you doing something like that?

PS: Is this a serious bug? I think when I do *data = ... the object apparently has a reference and should not be released when the method exits.

Yes. A serious bug in your code. If you read the documentation (www.developer.com, type "Arc" into the search box), something very similar to your code is shown there as an example how not to do it.

ssawgift
Mar 31, 2012, 12:23 AM
Okay...Thanks for all who replied.