2

我正在使用CoreLocation,并从我的应用程序AppDelegate中启动locationManager。示例代码如下...从其他ViewController的locationManager方法访问newLocation

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 - 我使用的Xcode4.3瓦特/ ARC

回答

2

要做到这一点,声明变量在你的appDelegate一个属性:在您的m

@property (nonatomic, retain) NSArray *array;

(@synthesize太)

然后在您的视图控制器,创建的appDelegate变量:

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

那么你可以做: NSLog(@"%@", appDelegate.array);

+0

啊,多美的东西。谢谢! – ElasticThoughts 2012-03-09 19:02:10

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

再次感谢!

+0

很好的解决方案,工作正常! – TharakaNirmana 2015-09-01 07:06:09