Objective C memory management

After a while finally (I think) I grasp how this memory management thing works in Objective C.

First about assign and retain.

When you declare properties using (retain) then the retain count will be incremented by one when you assign value to it.

@interface LayerA : CCLayer{

   CCSprite *sprite;
}

@property (retain) CCSprite *sprite;
@end

Now if in other classes you call:

LayerA.sprite = [CCSprite node];

The retain count of sprite in LayerA will be incremented by one and as such, it won't be released until you call:

LayerA.sprite = nil;

which will decrease the retain count by one. So everytime you assign a value to a retain property, you must have a matching nil assignment to it.

This can complicate manual memory management and I usually prefer to have assign instead of property.


@interface LayerA : CCLayer{

   CCSprite *sprite;
}

@property (assign) CCSprite *sprite;
@end

Now when you assign a value to the sprite property, the retain count will not be incremented.

Another case about memory management that I learnt the hard way was when passing argument to the class constructor.

When class A calls the constructor of class B and passes parameters, the parameters will be released when class A is released. So if class B caches those parameters, it is good only as long as class A lives. The constructor in class B needs to make deep copy of the parameter if class B wants to use the parameters in methods other than constructor.

0 komentar:

Posting Komentar