I’ve created an array to put my spriteFrame into and of course, I am trying to release the array after I use it so it won’t leak but whenever I put it below all my code, my app crashes and I get Bad Access Error Code 1. Here’s how I’m trying to release it:
-(void)moveHair {
NSMutableArray *animateHair = [NSMutableArray arrayWithCapacity:10];
for (int i = 1; i < 10; i++) {
NSString *animHair = [NSString stringWithFormat:@"wRightLong%i.png", i];
CCSpriteFrame *whiteFrame = [frame spriteFrameByName:animHair];
[animateHair addObject:whiteFrame];
}
CCAnimation *blowHair = [CCAnimation animationWithSpriteFrames:animateHair delay:0.15];
CCAction *blowingHair = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:blowHair]];
[white runAction:blowingHair];
[animateHair release];
animateHair = nil;
}
Why am I getting that error and how do I fix it?
You don’t need the final release. Remove these lines:
The reason is that you created your array like this:
In such,
NSMutableArray‘sarrayWithCapacity:method returns anautoreleasedobject.(By releasing it again, you’re actually releasing the retained array by your
CCAnimationobject… hence the next time it tries to access the array, you get the “Bad Access” exception as you noted.)Note:
In general, most of the
NSandUIclasses returnautoreleasedobjects from their class convenience creation methods. The exception is if the method has the wordneworcreatein it.You can make your life easier by using ARC (automatic retain count) instead. However, in my opinion, learning how memory management works is important to becoming an advanced developer in Objective-C. Here’s a tutorial from Ray Wenderlich’s site, if you’re interested:
http://www.raywenderlich.com/2657/memory-management-in-objective-c-tutorial