How return NSData object from a method?

Discussion in 'Mac Programming' started by ssawgift, Mar 28, 2012.

  1. ssawgift, Mar 28, 2012
    Last edited by a moderator: Mar 28, 2012

    macrumors newbie

    Joined:
    Mar 23, 2012
    #1
    I have ARC on for my test project, and one of my class has this method:

    Code:
    - (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:
    Code:
        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.
     
  2. macrumors 6502a

    Joined:
    Jan 23, 2010
    Location:
    San Diego, CA USA
    #2
    Why not just make the method:

    Code:
    - 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.
     
  3. macrumors 68030

    Catfish_Man

    Joined:
    Sep 13, 2001
    Location:
    Portland, OR
    #3
    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;
     
  4. gnasher729, Mar 29, 2012
    Last edited: Mar 29, 2012

    macrumors G5

    gnasher729

    Joined:
    Nov 25, 2005
    #4
    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?

    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.
     
  5. thread starter macrumors newbie

    Joined:
    Mar 23, 2012

Share This Page