Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS memory issue with init in viewDidLoad and release in viewDidUnload

Tags:

ios

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.

like image 492
MomentH Avatar asked Dec 09 '25 14:12

MomentH


1 Answers

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!

like image 186
Jiri Avatar answered Dec 12 '25 09:12

Jiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!