Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chen8002004

macrumors newbie
Original poster
May 22, 2011
26
0
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;
 
Last edited:

Cromulent

macrumors 604
Oct 2, 2006
6,802
1,096
The Land of Hope and Glory
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;

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).
 

chen8002004

macrumors newbie
Original poster
May 22, 2011
26
0
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;    }
 
Last edited by a moderator:

Cromulent

macrumors 604
Oct 2, 2006
6,802
1,096
The Land of Hope and Glory
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;    }

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;
 
Last edited by a moderator:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.