如何释放MPMoviePlayerController预加载内存

时间:2011-01-17 08:13:41

标签: iphone memory-leaks mpmovieplayercontroller

您好。 我在我的iPhone应用程序中使用MPMoviePlayerController有时会显示一些短视频剪辑。应用程序mainView中有一些按钮。当我按下按钮时,电影将播放。 当我按下按钮时,按钮调用[self playVideo:@“xxx”],视频显示正确。但是当我使用Instruments Allocations Tool看到应用程序时,我发现分配的内存最多可达8+ MB播放器播放完毕后不会取消分配。如果我按下按钮大约15次,ipad就会崩溃。负责分配的是负责任的图书馆,名为 CoreVideo 。也许内存在视频预加载时会泄漏但在完成后不会释放。我怎么能释放这些记忆。 以下是类别中的方法:

-(id)playVideo:(NSString* )videoName
{
    NSString* s = [[NSBundle mainBundle] pathForResource:videoName ofType:@"mp4"];
    NSURL* url = [NSURL fileURLWithPath:s];
    [self playVideoAtURL: url];
    s = nil;
    [s release];
    url = nil;
    [url release];
}


-(void)playVideoAtURL:(NSURL *)theURL
{
    theMovie = [[MPMoviePlayerViewController alloc] initWithContentURL:theURL];
    theMovie.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
    theMovie.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
    if (LeftOrRight == 0) {
        [theMovie.view setTransform: CGAffineTransformMakeRotation(degreesToRadians(-90))];
    }
    else if (LeftOrRight == 1) {
        [theMovie.view setTransform: CGAffineTransformMakeRotation(degreesToRadians(90))];
    }
    CGRect screenBounds = [[UIScreen mainScreen] bounds];  
    theMovie.view.frame = screenBounds;
    theMovie.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [theMovie.moviePlayer prepareToPlay]; 
    [self presentModalViewController: theMovie animated: YES]; 

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(myMovieFinishedCallback:)
                                                 name: MPMoviePlayerPlaybackDidFinishNotification
                                               object:nil]; 
}

-(void)myMovieFinishedCallback:(NSNotification *)aNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:nil];
    [theMovie  dismissMoviePlayerViewControllerAnimated];
    [theMovie.moviePlayer stop];
    [theMovie release];
}

谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码包含多个内存泄漏。

此处分配的字符串从未发布,因为您在发布之前将其设置为nil。

NSString* s = [[NSBundle mainBundle] pathForResource:videoName ofType:@"mp4"];
s = nil;
[s release];

调用playVideoAtURL方法时不释放MPMoviePlayerViewController

-(void)playVideoAtURL:(NSURL *)theURL
{
    // YOU HAVE MEMORY LEAK IN NEXT LINE!!!

    theMovie = [[MPMoviePlayerViewController alloc] initWithContentURL:theURL];

    ...
}

因此,如果电影没有完成,你分配新的MPMoviePlayerViewController实例,并且不会发布前一个实例。