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
nilin -dealloc.