Resolved Memory management of structs

Discussion in 'iPhone/iPad Programming' started by chen8002004, May 24, 2011.

  1. chen8002004, May 24, 2011
    Last edited: May 25, 2011

    macrumors newbie

    Joined:
    May 22, 2011
    #1
    Most discussion about memory management of Objective-C is based on classes derived from NSObject. How about the memory management of a struct? Is it similar to standard C++ memory management (using new and delete)? An example struct is shown as follows:
    Code:
    typedef struct
    {
        int startPosition;
        int endPosition;
        int Velocity;
    } carInfo;
     
  2. macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
    #2
    When creating it:

    Code:
    struct carInfo *car = malloc(sizeof(struct carInfo));
    when freeing it:

    Code:
    free(car);
    car = NULL;
    or you can just use a stack based struct:

    Code:
    struct carInfo car;
    and have no need to use manual memory management (although when it goes out of scope the object is automatically destroyed).
     
  3. chen8002004, May 25, 2011
    Last edited by a moderator: May 25, 2011

    thread starter macrumors newbie

    Joined:
    May 22, 2011
    #3
    Could I pass parameter like this?
    Code:
    struct carInfo *car = malloc(sizeof(struct carInfo));
    [self changeData: car];
    NSLog([NSString stringWithFormat:@"Car start position: %d", car->startPosition]);
    
    
    -(void) changeData: (carInfo*) myData
    {   myData->startPosition = 100;    }
     
  4. Cromulent, May 25, 2011
    Last edited by a moderator: May 25, 2011

    macrumors 603

    Cromulent

    Joined:
    Oct 2, 2006
    Location:
    The Land of Hope and Glory
    #4
    Yes, with this small change:

    Code:
    -(void) changeData: (struct carInfo*) myData
    you need to use a proper typedef to be able to remove the struct keyword.

    I prefer using typedefs in the following way rather than having them mixed in with the struct definition:

    Code:
    struct carStruct
    {
        int startPosition;
        int endPosition;
        int Velocity;
    };
    
    typedef struct carStruct carInfo;
     
  5. thread starter macrumors newbie

    Joined:
    May 22, 2011
    #5
    Many thanks for Cromulent's help. I think I am clear with this question now.:)
     

Share This Page