简体   繁体   中英

Re-Assigning an Autoreleased Object

I'm building a puzzle game that has three different sizes. The images that are loaded are dependent on the size of the puzzle. For simplicity's sake I'll call them small/medium/large. When I load my view, I'm telling it the size of the puzzle and I'm calling a loadImages method.

I have a property that's set up like this:

@property (nonatomic, retain) UIImage *solidSquare;

So in my loadImages method I have:

self.solidSquare = [[[UIImage alloc] initWithContentsOfFile:solidPath] autorelease];

solidPath is dynamically determined based on the puzzle size.

Now, if the user switches to a different puzzle size, I'm calling loadImages again when the game starts. How do I handle this memory situation? I feel like I need to call this at the beginning of my loadImages method.

[self.solidSquare release];

Do I? How do I evaluate if it's the very first time it's loaded, or do I even need to?

No, you don't (or it will crash). Since the object is autoreleased, you don't have to worry about its reference anymore -- it won't make its pointer dangling and won't leak memory. Also, when using properties, the property setter ensures the old object is automatically released.

All in all, you can safely reassign the property.

Edit: but you do have to set it to nil in -dealloc.

When you call autorelease, it adds the object to the autorelease pool, so you don't need to release it explicitly. If you would like to have control over when the object is released, don't call autorelease and release the object wherever you see fit.

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