有谁知道为什么 xCode 的“构建和分析”会将此行报告为“可能的内存泄漏”?
goodSound = [[SoundClass alloc] initializeSound:@"Good.wav"];
/////以下是有问题的 4 个文件:
// Sounds.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
@interface SoundClass : NSObject
{
SystemSoundID soundHandle;
}
-(id) initializeSound:(NSString *)soundFileName;
-(void) play;
@end
//////////////
// Sounds.m
#import "Sounds.h"
@implementation SoundClass
-(id) initializeSound:(NSString *)soundFileName
{
self = [super init];
NSString *const resourceDir = [[NSBundle mainBundle] resourcePath];
NSString *const fullPath = [resourceDir stringByAppendingPathComponent:soundFileName];
NSURL *const url = [NSURL fileURLWithPath:fullPath];
OSStatus errCode = AudioServicesCreateSystemSoundID((CFURLRef) url, &soundHandle);
if(errCode == 0)
NSLog(@"Loaded sound: %@", soundFileName);
else
NSLog(@"Failed to load sound: %@", soundFileName);
return self;
}
//////////////////////////////
-(void) play
{
AudioServicesPlaySystemSound(soundHandle);
}
/////////////////////////////
-(void) dealloc
{
AudioServicesDisposeSystemSoundID(soundHandle);
[super dealloc];
}
/////////////////////////////
@end
///////////////
// MemTestViewController.h
#import <UIKit/UIKit.h>
@class SoundClass;
@interface MemTestViewController : UIViewController
{
SoundClass *goodSound;
}
-(IBAction) beepButtonClicked:(id)sender;
@end
///////////
// MemTestViewController.m
#import "MemTestViewController.h"
#import "Sounds.h"
@implementation MemTestViewController
- (void)viewDidLoad
{
NSLog(@"view did load: alloc'ing mem for sound class");
// "build and analyze" says this is possibly a memory leak:
goodSound = [[SoundClass alloc] initializeSound:@"Good.wav"];
[super viewDidLoad];
}
-(IBAction) beepButtonClicked:(id)sender
{
NSLog(@"beep button clicked");
[goodSound play];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
[goodSound release];
[super dealloc];
}
@end
最佳答案
这可能是内存泄漏。如果 View 被卸载,viewDidLoad
可能会被调用任意多次,在这种情况下,每次都会泄漏内存。为了进行保护,您可以释放 viewDidUnload
中的内存并将 ivar 设置为 nil,或者仅当 ivar 实际上为 nil 时才在 viewDidLoad
中初始化声音。
所以:
- (void)viewDidLoad
{
if( !goodSound )
goodSound = [[SoundClass alloc] initializeSound:@"Good.wav"];
[super viewDidLoad];
}
和/或:
- (void)viewDidUnload
{
[goodSound release];
goodSound = nil;
[super viewDidUnload];
}
关于iphone - Xcode 的 "build and analyze"报告此代码存在奇怪的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3326726/