不确定这是否是模拟器问题或者我遗漏了什么,下面的代码给我一个内存泄漏,尽管theAudio是在dealloc中发布的。我正在播放.wav文件,声音会根据整数的值而改变。应用程序运行正常,但我在xcode
中测试时标记了16位泄漏非常感谢任何建议:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface Water : UIViewController
<AVAudioPlayerDelegate>
{
}
@property (nonatomic,retain) AVAudioPlayer *theAudio;
-(IBAction) goButMenu: (id) sender;
-(IBAction) goDrinkMenu: (id) sender;
-(IBAction) playwater;
@end
@implementation Water
@synthesize theAudio;
-(IBAction) goDrinkMenu: (id) sender{
ButDrinkMenu *butdrinkmenu1 = [[ButDrinkMenu alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:butdrinkmenu1 animated:YES];
}
-(void) viewDidLoad {
if (BoyOrGirl == 1) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Applause" ofType:@"wav"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
else {
NSString *path = [[NSBundle mainBundle] pathForResource:@"bongo" ofType:@"wav"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
}
-(IBAction) playwater{
if (BoyOrGirl == 1) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Applause" ofType:@"wav"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
else {
NSString *path = [[NSBundle mainBundle] pathForResource:@"bongo" ofType:@"wav"];
theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
}
答案 0 :(得分:0)
直接在设备上进行测试;使用模拟器测试泄漏可能会返回不准确的结果。
也就是说,此代码示例存在一些与内存相关的问题。您可能希望在此处包含您的dealloc方法,因为这可能提供一些见解,但这是一个问题(出现在您的几个分配中):
您的AVAudioPlayer未分配给您的媒体资源,也未在范围内发布。理想情况下,玩家分配看起来更像:
AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc] initWithContents....
[myPlayer setDelegate:self];
[self setTheAudio:myPlayer];
[myPlayer release];
与你实现它的方式相反,它直接为玩家分配实例变量:
theAudio = [[AVAudioPlayer alloc] initWith...
因为您将播放器直接分配给您的实例变量,所以您的播放器不会被保留。如果您尝试正确平衡呼叫,这可能会导致过早释放和悬空指针,否则会导致泄漏。