Scope of an object, objective

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.


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.

链接地址: http://www.djcxy.com/p/20340.html

上一篇: 无法分配CLLocationManager

下一篇: 客体的范围