CoreLocation behaviour

For many months, I couldn’t figure out why this CoreLocation delegate method is called twice whenever I click a “get current location” button on my app.

– (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

Today, I figured it out.

- (IBAction)getCurrentLocation:(id)sender
    if( [m_locationManager locationServicesEnabled] )
        // stopUpdatingLocation is supposed to be called only
        // when you don't need CoreLocation service any more.

        //[m_locationManager stopUpdatingLocation];

        // However, startUpdatingLocation is to be called
        // whenever you want to get the current location information.
        [m_locationManager startUpdatingLocation];

The CoreLocation provides only two instant messages, i.e. startUpdataingLocation and stopUpdatingLocation. If you have used other APIs like OpenGL, you would noticed that similar pattern. Let the system know you are about to use the service, use them, and clarify that you finished using it.
So, according to the pattern, startUpdatingLocation and stopUpdatingLocation look like falling in that pattern. So, because there are only two methods, I thought that I should always call stopUpdatingLocation to use startUpdatingLocation. However, it turned out that I was wrong.

So, if you call the stopUpdatingLocation, the delegate method is called once, and when the startUpdatingLocation is called, the delegate method is called again.
Because there is no need to call stopUpdatingLocation there, you can comment it out like the code above, then the delegate method will be called only once.

The delegate method to be called

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: