I'm implementing a simple button-sound interface for a toy project. There are multiple buttons, with individual sounds assigned to each button. I accomplish this all within the fooViewController.{h,m} with the 'tag' attribute of each UIButton like so:
B0.tag = 0;
B1.tag = 1;
...
I also have an array of sound files, which I hold inside an array of strings, populated as follows:
sounds[0] = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"caf"];
sounds[1] = [[NSBundle mainBundle] pathForResource:@"bar" ofType:@"caf"];
...
Now when a button Touch Up Inside event is triggered, the following method fires:
-(IBAction)playSoundClip:(id)sender {
if(sounds[[sender tag]] != nil) {
NSError *error;
NSString *temp = [sounds[[sender tag]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AVAudioPlayer *av = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:temp] error:&error];
[av play]
}
}
I always receive a EXC_BAD_ACCESS exception. When I print out the strings, they are in tact, and as can be expected.. a few spaces, which I thought would be taken care of by the string encoding ^above.
You are populating the C
array with autoreleased objects. Since you are not taking ownership of the objects, they would have been released soon after assignment.
My recommendation is to use an NSArray
instance to hold your paths. It will automatically retain them when you add the path.