I need help with my iOS application ^^,. I want to know if I’m releasing AVAudioPlayer correctly.
MyViewController.h
#import <UIKit/UIKit.h>
@interface MyViewController : UIViewController
{
NSString *Path;
}
- (IBAction)Playsound;
@end
MyViewController.m
#import <AVFoundation/AVAudioPlayer.h>
#import "MyViewController.h"
@implementation MyViewController
AVAudioPlayer *Media;
- (IBAction)Playsound
{
Path = [[NSBundle mainBundle] pathForResource:@"Sound" ofType:@"wav"];
Media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:Path] error:NULL];
[Media play];
}
- (void)dealloc
{
[Media release];
[super viewDidUnload];
}
@end
I think that the way you’ve implemented your solution could be better and understanding why will help you learn.
First, it’s convention in Objective-C (at least Cocoa and Cocoa Touch) to name variables and method names starting with a lowercase letter. For example, your “Media” variable should be “media” and your “PlaySound” method should be “playSound”.
Second, your “media” variable is declared as a global variable and it would be better to declare it as an instance variable in the
@interfacein your MyViewController.h file. Thus, each instance ofMyViewControllerwould have an instance variable called “media” which better fits the object-oriented concept of encapsulation. Personally, I would call the variable “player” because it seems to me to describe what the variable is better (I’ll use “player” from here on out).Third, if your “playSound” is always going to play the same sound as you have it, it may be better to move your allocation of the “media” object to the “init…” method (e.g., initWithNibName:bundle: method). This way you instantiate the object only once and not each time your “playSound” method is called (I presume that it can be called multiple times). You’re “playSound” method would only need to call
[player play]. This way there’s really no reason to have your path as an instance variable.Last, if you do things as above then calling [player release] in the dealloc method makes sense. The dealloc method is called when an instance of the class is deallocated and that deallocates the instance of “player” that belongs to it.
Here’s what my changes would look like.
MyViewController.h
MyViewController.m