In my “connect4” style game I have an array representing a 7×6 grid, each “cell” in the array contains either NSNull or a UIView subclass ‘CoinView’. Is the following the correct way to remove objects from the NSMutableArray and the primary view?
- (IBAction)debugOrigin:(id)sender {
int x = 0;
int y = 0;
//get the coin object form the grid
CoinView *coin = [[grid objectAtIndex:x] objectAtIndex:y];
//cancel if there's no coin there
if ([coin isKindOfClass:[NSNull class]]) { return; }
//remove the coin from memory
[coin removeFromSuperview];
coin = nil;
[[grid objectAtIndex:x] setObject:[NSNull null] atIndex:y]; //will this leak?
}
Thanks!
Your code will not leak, and is in fact (almost) correct.
You should remove this comment, as you’re not dealing with memory in your code (and it may end up confusing you as to what the code really does):
In the following line you’re removing the view referenced by local variable “coin” from its superview:
And you assign nil to your local variable coin, which is good practice to make sure it’s not being used later in the code:
As far as I know there is no
setObject:AtIndex:for NSMutableArray. UsereplaceObjectAtIndex:withObject:instead:As a last note, I recommend that you read up a bit on memory management and memory leaks (from Apple’s developers documentation). The first offers you some hints and tips that make memory management much easier to understand.