I'm trying to prevent a memory leak. I have the code below but it crashes the phone when I place [theAudio release]; in there. If I take it out everything works fine but then it leaks. Can anyone see what is the problem?
.h
.m
.h
Code:
#import "FlipsideViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
NSString *titleForButton;
NSString *imagePath;
NSString *musicPath;
UIImageView *imageView;
UIScrollView *scrollView;
AVAudioPlayer *theAudio;
AVAudioPlayer *newAudio;
NSURL *fileURL;
UIButton *playBtn;
}
@property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
@property (nonatomic, retain) IBOutlet UIButton *playBtn;
@property (nonatomic, retain) AVAudioPlayer *theAudio;
- (IBAction)showInfo:(id)sender;
- (IBAction) selectLick:(id)sender;
- (IBAction) playLick: (id)sender;
@end
.m
Code:
#import "MainViewController.h"
@implementation MainViewController
@synthesize scrollView;
@synthesize theAudio;
@synthesize playBtn;
-(IBAction) selectLick:(id)sender {
titleForButton = [sender titleForState: UIControlStateNormal];
imagePath = [[NSString alloc] initWithFormat:@"%@.png", titleForButton];
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imagePath]];
[imagePath release];
[scrollView setCanCancelContentTouches:NO];
scrollView.clipsToBounds = YES;
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
[[scrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
[scrollView addSubview:imageView];
[scrollView setContentSize:CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)];
[imageView release];
[scrollView setScrollEnabled:YES];
[newAudio stop];
[playBtn setTitle:@"Listen" forState:(UIControlState)UIControlStateNormal];
musicPath = [[NSBundle mainBundle] pathForResource:titleForButton ofType:@"mp3"];
fileURL = [[NSURL alloc] initFileURLWithPath: musicPath];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
newAudio = theAudio;
[COLOR="Red"][theAudio release];[/COLOR]
[fileURL release];
[newAudio setDelegate: self];
[newAudio prepareToPlay];
}
-(IBAction) playLick: (id) sender {
if (newAudio.isPlaying) {
[newAudio pause];
[sender setTitle:@"Listen" forState:(UIControlState)UIControlStateNormal];
}
else {
[newAudio play];
[sender setTitle:@"Pause" forState:(UIControlState)UIControlStateNormal];
}
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)newAudio successfully:(BOOL)flag
{
[playBtn setTitle:@"Listen" forState:(UIControlState)UIControlStateNormal];
}