从一个viewcontroller访问另一个viewcontroller的CLLocationManager变量

时间:2014-12-15 15:28:38

标签: ios objective-c core-location cllocationmanager

我是ios的新手。我已经像这样声明了CLLocationManager变量

DashBoardViewController.h

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@class AppDelegate;
@interface DashBoardViewController : UIViewController<CLLocationManagerDelegate, UIAlertViewDelegate>{

    AppDelegate *appDel;
}
@property(nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,retain) CLLocation *current;

-(void)localnotification;
@end

在DashBoardViewController.m文件中:

#import "DashBoardViewController.h"
#import "AppDelegate.h"

#define IS_OS_8_OR_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)

@interface DashBoardViewController ()
@end

@implementation DashBoardViewController

@synthesize current,locationManager;
- (void)viewDidLoad
{
    [super viewDidLoad];
    appDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [self localnotification];
}

-(void)localnotification{ 
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;

    if(IS_OS_8_OR_LATER) {
        [locationManager requestAlwaysAuthorization];
    }

    [locationManager startMonitoringSignificantLocationChanges];
}

我也实施了

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
  //some code
}

现在我正在访问“locationManager”“localnotification”这样的方法 SettingsViewController.m

#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import "DashBoardViewController.h"

//To stop the Location Manager service
- (IBAction)stopButtonAction:(id)sender {
DashBoardViewController *dash=[[DashBoardViewController alloc] init];
    dash.locationManager=nil;
}

//To start the Location Manager service
- (IBAction)startButtonAction:(id)sender {

    DashBoardViewController *dash=[[DashBoardViewController alloc] init];
    [dash localnotification];
}

但它不起作用。所有时间locationManager都返回null。这段代码怎么了?请帮忙。

2 个答案:

答案 0 :(得分:3)

当您对视图控制器进行alloc-init时,不会调用viewDidLoad。在加载视图时会调用它,稍后在实际显示时会调用它。这就是为什么它是零。如果要跨多个视图控制器访问它,我建议在AppDelegate中创建位置管理器。

答案 1 :(得分:3)

当你

DashBoardViewController *dash=[[DashBoardViewController alloc] init];

它会创建一个新的DashBoardViewController实例。您可以在locationManager中定义AppDelegate,然后从代码中的任意位置直接访问它。

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