0
votes

I'm still pretty new to programming so I have somewhat of a noob question. When you have an instance variable, in my case of type CLLocationManager, in my appDelegate.m file, I thought I could allocate and initialize my CLLocationManager instance variable in the applicationDidFinishLaunching method. And then I could use a button to startUpdatingLocation in a different method (since I'm calling it from another class). This doesn't seem to work and I'm thinking that I needed to alloc/init in the same method I startUpdatingLocation. Is that true? Do I need to stopUpdatingLocation in the same method? My code is below:

(locationManager is declared as a property)


- (void)stopUpdating {
    [locationManager stopUpdatingLocation];
}

- (double)distanceTraveled {
    return distanceTraveled;
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after application launch
    [window addSubview:rootController.view];    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [window makeKeyAndVisible];
}

- (void)startUpdating {
    [locationManager startUpdatingLocation];
}

It seems like I should be doing it more like:

- (void)startUpdating {
locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}

If I am supposed to do it this second way, is it because that the scope of the CLLocationManager object is only for the method it is in? I thought having it as an instance variable I would be able to use it in other methods and I could have a separate method for startUpdatingLocation and stopUpdatingLocation. Thanks.

1
Not to detract from your question too much, but please understand that the application delegate should not be used for this kind of thing. Ad this to a controller that makes the most sense (i.e., depending on your hierarchy, perhaps it makes sense to have it in your root view controller instead). The app delegate has a finite purpose: To set up your application, and handle specific events only. Its your job to do the rest, elsewhere.jer
Ok. I guess I assumed that part of the appDelegate was to set up your application like turning GPS on, but I see your point. Will change it.Crystal

1 Answers

2
votes

What you originally thought is correct. If you have an instance variable that variable remains available to you throughout the life of the object (in this case your app delegate).

If what you're doing isn't working, it's because of some other issue. you don't need to allocate a new CLLocationManager each time you call startUpdating.