从一个视图控制器访问 CLLocationManager 变量到另一个视图控制器

Posted

技术标签:

【中文标题】从一个视图控制器访问 CLLocationManager 变量到另一个视图控制器【英文标题】:Accessing CLLocationManager variable from one viewcontroller to another viewcontroller 【发布时间】:2014-12-15 15:28:38 【问题描述】:

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。这段代码有什么问题?

【问题讨论】:

【参考方案1】:

当你

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

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

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

【讨论】:

【参考方案2】:

在你分配初始化视图控制器时不会调用viewDidLoad。它在加载视图时调用,稍后在您实际显示它时完成。这就是为什么它为零。如果您想跨多个视图控制器访问它,我建议在 AppDelegate 中创建位置管理器。

【讨论】:

以上是关于从一个视图控制器访问 CLLocationManager 变量到另一个视图控制器的主要内容,如果未能解决你的问题,请参考以下文章

如何从关闭命令访问前一个视图控制器

从 Swift 3 中的另一个项目访问视图控制器

从一个视图控制器访问一组图像到另一个视图控制器,以添加滑动手势识别器

从主视图控制器访问模态视图控制器中的 UITextField 中的文本

IPHONE 如何从其他类/视图控制器访问变量

从不同的视图控制器访问变量