ios - 从一个 View Controller 访问 CLLocationManager 变量到另一个 View Controller

标签 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" 方法,如下所示 设置 View Controller .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。这段代码有什么问题?

最佳答案

当你

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

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

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

关于ios - 从一个 View Controller 访问 CLLocationManager 变量到另一个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27487437/

相关文章:

objective-c - 对多个地址进行地理编码 - CLGeocoder

ios - 即使在 iOS 11 中调用停止更新,bluebar 也会永远存在

iphone 开发 : when I analyze my app I have potential leak issue

自动更新订阅的定期付款的 iOS Webhook/通知

ios - 根据屏幕分辨率动态字体大小、样式

ios - 如何更改tableView单元格textLabel的宽度

iphone - Objc_msgSend 和应用程序崩溃

iOS 以编程方式将 AVI 转换为 MP4 格式

ios - GPUImage 第一次模糊时速度很慢

swift - 操作无法完成。 (kCLErrorDomain 错误 1。)