PDA

View Full Version : [Resolved] Memory management of structs




chen8002004
May 24, 2011, 11:37 PM
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:
typedef struct
{
int startPosition;
int endPosition;
int Velocity;
} carInfo;



Cromulent
May 25, 2011, 06:03 AM
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:
typedef struct
{
int startPosition;
int endPosition;
int Velocity;
} carInfo;

When creating it:

struct carInfo *car = malloc(sizeof(struct carInfo));

when freeing it:

free(car);
car = NULL;

or you can just use a stack based struct:

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
May 25, 2011, 06:35 AM
Could I pass parameter like this?
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; }

Cromulent
May 25, 2011, 09:05 AM
Could I pass parameter like this?
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:

-(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:


struct carStruct
{
int startPosition;
int endPosition;
int Velocity;
};

typedef struct carStruct carInfo;

chen8002004
May 26, 2011, 01:33 AM
Many thanks for Cromulent's help. I think I am clear with this question now.:)