Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in iOS, AVPlayer is never deallocated

I used the AVPlayerDemo sample from the Apple docs and wrote my own UI on top of it to play videos selected from a UITableViewController. Now, the problem is that there's a memory leak here somewhere which I can't find out. The problem is that the AVPlayer object is not being dealloced, I guessed this because every time a press back button and select a new video to play, there is a huge jump in the total memory consumed by the app which is show here:

The first time the video is player, the memory usage is 36.6MB

The first time the video is player, the memory usage is 36.6MB, now for the second time:

Here it has jumped to 58.2MB

Here it has jumped to 58.2MB, and keeps on increasing every time i go back and play the video again or a different video.

enter image description here

I have tried using Instruments with Leaks but haven't yet been able to figure out whats wrong with it.

Heres the whole Controller file code.

//EDIT

-(void) viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    if(_player.rate == 1.0){
        [_player pause];
    }

    [idleTimer invalidate];

    if(mTimeObserver){
        [_player removeTimeObserver:mTimeObserver];
        mTimeObserver = nil;
    }
    [_playerItem removeObserver:self forKeyPath:kStatusKeyT];
    [[NSNotificationCenter defaultCenter] removeObserver:self                                                 name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];


    _player = nil;
    _playerItem = nil;
    idleTimer = nil;
    _tapGestureRecognizer = nil;
}

-(void) dealloc
{
    NSLog(@"DEALLOCING");
}
like image 782
Faraz Hassan Avatar asked Jul 18 '14 08:07

Faraz Hassan


People also ask

How memory leak happens in iOS?

Memory that was allocated at some point, but was never released and is no longer referenced by your app. Since there are no references to it, there's now no way to release it and the memory can't be used again. So a memory leak occurs when a content remains in memory even after its life cycle has ended.

What is a memory leak Swift?

A memory leak occurs in an iOS app when memory that is no longer in use is not properly cleared and continues taking up space. This can hurt app performance, and eventually, when the app runs out of available memory, will cause a crash.


1 Answers

I had the same issue as you, but I managed to fix the memory leak by calling this on viewDidDisappear:

self.avPlayer?.replaceCurrentItem(with: nil)
like image 50
ThomasCle Avatar answered Sep 28 '22 17:09

ThomasCle