从其他ViewController的locationManager方法访问newLocation

Ela*_*hts 2 iphone objective-c core-location cllocationmanager cllocation

我正在使用CoreLocation并从我的应用程序AppDelegate中启动locationManager.示例代码如下......

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ...

    // start location manager
    if([CLLocationManager locationServicesEnabled])
    {
        myLocationManager_ = [[CLLocationManager alloc] init];
        myLocationManager_.delegate = self;
        [myLocationManager_ startUpdatingLocation];
    }
    else 
    {
        // ... rest of code snipped to keep this short
Run Code Online (Sandbox Code Playgroud)

在这种方法中,我们看到更新的位置.

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSString *currentLatitude = [[NSString alloc] initWithFormat:@"%g", newLocation.coordinate.latitude];
    NSLog(@"AppDelegate says: latitude: %@", currentLatitude);

    // ... rest of code snipped
Run Code Online (Sandbox Code Playgroud)

现在,在我的应用程序的其他区域中,我需要确定用户当前位置(纬度,经度).我可以结合上面的代码到需要当前位置的ViewControllers但后来我不得不CLLocationManager的多个实例运行(我认为) - 为什么复制此代码?有没有办法,从其他ViewControllers,我可以从AppDelegate获取位置信息?

PS - 我正在使用Xcode 4.3 w/ARC

Ela*_*hts 6

谢谢mohabitar为我回答这个问题!为了清楚起见,我已经发布了我的代码供其他人欣赏.

注意:只有相关部件如下所示.

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) CLLocationManager *myLocationManager;
@property (nonatomic, strong) CLLocation *currentLocation;
Run Code Online (Sandbox Code Playgroud)

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    if([CLLocationManager locationServicesEnabled])
    {
        currentLocation_ = [[CLLocation alloc] init];

        myLocationManager_ = [[CLLocationManager alloc] init];
        myLocationManager_.delegate = self;
        [myLocationManager_ startUpdatingLocation];
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    currentLocation_ = newLocation;
}
Run Code Online (Sandbox Code Playgroud)

其他ViewControllers.h

@property (strong, nonatomic) CLLocation *currentLocation;
Run Code Online (Sandbox Code Playgroud)

其他ViewControllers.m

- (void)viewDidLoad
{
    [super viewDidLoad];

    if([CLLocationManager locationServicesEnabled])
    {
        AppDelegate *appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
        currentLocation_ = [[CLLocation alloc] initWithLatitude:appDelegate.currentLocation.coordinate.latitude longitude:appDelegate.currentLocation.coordinate.longitude];
    }
}
Run Code Online (Sandbox Code Playgroud)

再次感谢!