从其他ViewController的locationManager方法访问newLocation

时间:2012-03-09 17:18:19

标签: 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

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

-(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

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

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

2 个答案:

答案 0 :(得分:6)

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

注意:只有相关部分如下所示。

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) CLLocationManager *myLocationManager;
@property (nonatomic, strong) CLLocation *currentLocation;

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;
}

其他ViewControllers.h

@property (strong, nonatomic) CLLocation *currentLocation;

其他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];
    }
}

再次感谢!

答案 1 :(得分:2)

为此,请将变量声明为appDelegate中的属性:

@property (nonatomic, retain) NSArray *array;

(@在你的.m中合成)

然后在视图控制器中,创建一个appDelegate变量:

AppDelegate *appDelegate=(AppDelegate*)[[UIApplication sharedApplication] delegate];

然后你可以这样做: NSLog(@"%@", appDelegate.array);