Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory leak in GMSMapView

I have created a simple UIViewController that creates and destroys a GMSMapView.

- (void)viewDidAppear:(BOOL)animated
{
  if ( !m_disappearing_bc_segue )
    {
       [super viewDidAppear:animated] ;

       GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude: self.location.latitude
                                                           longitude: self.location.longitude
                                                                zoom:9 ] ;

       m_mapView = [GMSMapView mapWithFrame:CGRectMake(0, 0, 320, 420) camera:camera];

       m_mapView.myLocationEnabled = NO ;

       [m_mapView setMapType: kGMSTypeTerrain] ;

       m_mapView.delegate = self ;

      [self.view addSubview:m_mapView] ;
      [self.view sendSubviewToBack:m_mapView] ;
}



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

  [m_mapView clear] ;
  [m_mapView stopRendering] ;
  [m_mapView removeFromSuperview] ;
  m_mapView = nil ;
}

I have used Instruments with the Allocations instrument. The test is easy. In a UINavigation ViewController, push the view, hit back and repeat. There is about 40kb leak each time you push and pop the view containing the GMSMapView described above. I have an screenshot from the Instruments to illustrate this, but stackoverflow does not allow me to post it. I can send to someone by email if interested.

Am I doing something wrong or missing out something?

like image 845
user2101384 Avatar asked Mar 15 '13 23:03

user2101384


1 Answers

What worked for me was removing the @try clause I had in dealloc:

@try {
    [self.mapView removeObserver:self forKeyPath:@"myLocation"];
}
@catch (NSException *exception) {
}

My intention was to remove self as observer when the ViewController is dealloc'd (ironically to avoid a memory issue), and ignore the exception if it is not an observer.

Apparently @try somehow retains the mapView, which makes it stay in memory (via ARC). See why here: Why does "try catch" in Objective-C cause memory leak?.

After removing @try clause (and conditioning the removeObserver with some flag to avoid the exception), the memory went back to behave normally!

like image 60
mllm Avatar answered Nov 15 '22 13:11

mllm