Search code examples
objective-ciosmemory-managementretainassign

Retain/assign memory management


I'm trying to understand memory management on iOS. I created this interface:

@interface Player : NSObject {
    PlayerType pType;
    PlayerWeapon pWeapon;
}

@property(nonatomic, readwrite, retain) pType;
@property(nonatomic, readwrite, retain) pWeapon;

@end

and this in the implementation file:

@synthesize pType;
@synthesize pWeapon;

In the header file, I use the retain property because pType and pWeapon are not standard C structs. From what I understand, if they were C structs, I would use assign instead. Since I've used retain, does that mean this class retains the object or whichever class instantiates it? For example, if I do this in another class:

Player *player = [[Player alloc] init];

Does this new class have to call [player release] or will the object automatically be released?


Solution

  • A good, general rule is that whatever you alloc/init or copy you have "created" and own, therefore you will have to release it. So yes, the object that owns player will need to release it when it is done using it. This applies if the Player object is created just for a local scope within a method, or if it is an ivar.

    Remember though, that if you ever decide to create an autoreleased Player object, you will need to retain the object either through the property dot syntax or an actual retain message to keep the Player object from being autoreleased after the local method has finished executing.

    // Retaining an autoreleased object
    self.player=[Player playerWithName: @"George"];
    

    or

    player=[[Player playerWithName:  @"George"] retain]; 
    

    Good luck