3

Are there any potential memory issues with the following code?:

- (void)viewDidLoad
{ 
    locationManager = [[CLLocationManager alloc] init];
}

- (void)viewWillAppear:(BOOL)animated {

    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    [locationManager startUpdatingLocation];
}

- (void)viewDidUnload
{
    [locationManager release];
    locationManager=nil;
    [super viewDidUnload];
}

I have checked it with Instrument and it says there is memory leaking with above code.

Kev
  • 118,037
  • 53
  • 300
  • 385
MomentH
  • 1,979
  • 5
  • 22
  • 24

2 Answers2

5

You should release the locationManager in the dealloc method.

- (void)dealloc
{
    [locationManager release];
    [super dealloc];
}

The reason for that is that viewDidUnload is not guaranteed to get called.

For details see these questions:

When is UIViewController viewDidUnload called?

viewdidunload is not getting called at all!

Community
  • 1
  • 1
Jiri
  • 2,206
  • 1
  • 22
  • 19
  • You are right... I have checked it with Instrument and there was a memory leaking with above code I posted.. That's why I am asking this question... It seems to work fine with dealloc.. – MomentH Sep 21 '11 at 14:46
0

It looks quite well besides:

  1. At the beginning of viewDidLoad add [super viewDidLoad];.
  2. At the beginning of viewWillAppear: add [super viewWillAppear:animated];
Nekto
  • 17,837
  • 1
  • 55
  • 65