How can i use a variable created in a objective c Void function?
Im trying to get the lat and long values generated in a void function and use them within another function. Any help grateful.
- (void)locationManager:(CLLocationManager *)manager
开发者_如何学编程 didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
float latDeg = newLocation.coordinate.latitude;
NSLog(@"Lat: %g", latDeg);
float longDeg = newLocation.coordinate.longitude;
NSLog(@"Lat: %g", longDeg);
}
I want to use the latDeg and longDeg variables.
Declare latDeg
and longDeg
as instance variables in your class. Declaring properties for the instance variables and using them for every access of the variable is optional, but recommended.
If you want to reuse them in the same class, you can just declare them after implementation of you class. For example `@implementation LocationClass float latDeg; float longDeg
(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { latDeg = newLocation.coordinate.latitude; NSLog(@"Lat: %g", latDeg);
longDeg = newLocation.coordinate.longitude; NSLog(@"Lat: %g", longDeg); } ` that's enough. Or you can declare them in you AppDelegater and then use them like:
YourAppDelegate delegate; delegate = (YourAppDelegate) [[UIApplication sharedApplication] delegate]; float currVar = [delegate->longDeg];
a) Make them global variables
b) Make that LocationManager a property of the class you're using it in. You now can add two double-properties to that came class where you might save your latitude or longitude in.
c) Extend your function with another function that takes the lat and lon and writes them to a variable at wherever you need it.
I would highly recommend version b, since it's not only the most simple and cleanest, but it's the only one that does not most likely hurt the OCP at some point.
精彩评论