As a relative Objective-C beginner, I’m obviously still not grasping certain memory management rules. I can’t figure out how to make this not crash:
@interface MyClass { NSArray *playerArray4th; }
- (void) viewDidLoad { playerArray4th = [self getAudioPlayersForSoundFile:@"rimshot" ofType:@"aif"]; }
- (NSArray*) getAudioPlayersForSoundFile:(NSString*)soundFileName ofType:(NSString*)soundFileType {
//code instantiating objects....
NSArray *toRet = [[NSArray alloc] initWithObjects:toRetTickPlayer,toRetTickPlayerCopy,toRetTickPlayerCopy2,toRetTickPlayerCopy3, nil];
return toRet;
}
Then later, in a different function:
NSArray *currentArray = playerArray4th;
[currentArray release];
currentArray = nil;
currentArray = [self getAudioPlayersForSoundFile:fileName ofType:ofType];
And it crashes when trying to access the array again:
- (void) playSound:(NSString*)soundType {
AVAudioPlayer *currentPlayer;
if ([soundType isEqualToString:@"4th"]) {
if (playerArray4thCounter >= [playerArray4th count]) playerArray4thCounter = 0;
NSLog(@"Playing from array: %@",playerArray4th);
currentPlayer = [playerArray4th objectAtIndex:playerArray4thCounter];
playerArray4thCounter++;
}
}
Try to learn about
propertiesand about using getters and setters. Don’t take shortcuts unless you know exactly what’s going on.So define the
playerArray4thproperty in your header file:And then in your
.mfile create getter/setter:Then, always use
self.playerArray4thfor assigning and getting the variable. The prior objects will be released when needed.So this will not leak:
because the second assignment releases the first array.
Furthermore, read about using
autorelease. In short, if youalloc,copyornew, you should eitherreleaseorautorelease. There’s a lot to read about this here on SO which I will not repeat here now.Don’t forget to put
self.playerArray4th = nil;in yourdeallocmethod.