简体   繁体   中英

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?

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

When you make a property "retained" the compiler generated setter method takes responsibility of making sure objects are release and retained correctly. This property essentially handles the work of releasing the previous object it was referencing and retains (takes ownership) of the object that was assigned. You will also need to add the following code in the implementation file to release these objects when the Player object is released:

- (void) dealloc
{
    [pType release];
    [pWeapon release];
    [super dealloc];
}

This means that even though the internal properties are "retained," when a "Player" object is allocated, you will still have to release it at some point.

The caller of [[Player alloc] init] is responsible for sending the new Player object a release message. The Player object's properties don't affect that responsibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM