3

I have the following code in my iPhone application, warning memory leak!

This is my code

-(IBAction)playVideo:(id)sender  {  
     NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"test" 
                                                              ofType:@"mov"];  
     NSURL    *fileURL    =   [NSURL fileURLWithPath:filepath];  
     MPMoviePlayerController *moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
    [moviePlayerController.view setFrame:CGRectMake(38, 100, 250, 163)];  
    [self.view addSubview:moviePlayerController.view];  
    moviePlayerController.fullscreen = YES;  
    [moviePlayerController play];  
} 

This is the error message I'm getting: Potential leak of an object allocated on line 37 and stored into 'moviePlayerController'

I did try to autorelease "moviePlayerController" and then I try to release it. Both cases memory leak was solved but the video didn't play on the iPhone! Strange please help.

Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60
HardCode
  • 99
  • 2
  • 8
  • possible duplicate of [How to release MPMoviePlayerController?](http://stackoverflow.com/questions/695307/how-to-release-mpmovieplayercontroller) – albertamg Sep 07 '11 at 15:07

2 Answers2

4

The warning is correct: you are leaking the MPMoviePlayerController instance. But as you've discovered, you can't effectively use the view without keeping the controller around.

The solution is to store the MPMoviePlayerController into an ivar/property in your class, and then release it when you are done with its view (e.g. in viewDidUnload and dealloc).

Anomie
  • 92,546
  • 13
  • 126
  • 145
0

try adding MPMoviePlayerController *moviePlayerController in your header file

then @property (nonatomic, retain) MPMoviePlayerController *moviePlayerController;

then in your .m file @synthesize moviePlayerController;

then try self.moviePlayerController = [[[MPMoviePlayerController alloc] initWithContentURL:fileURL] autorelease];

lastly add self.moviePlayerController = nil and [moviePlayerController release] to your viewDidUnload and dealloc.

Dhruv
  • 2,153
  • 3
  • 21
  • 45
Jiho Kang
  • 2,482
  • 1
  • 28
  • 38