CLLocationManager没有在NSObject中调用委托

问题描述 投票:5回答:1

我正在尝试创建一个帮助程序类,以便轻松地在任何其他类中获取手机的坐标。我遵循了一个教程,其中UIViewController实现了<CLLocationManagerDelegate>并且它有效。我试图在一个简单的NSObject做同样的事情,但后来我的代表不再被召唤了。

这是我的代码:

PSCoordinates.h

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

@interface PSCoordinates : NSObject <CLLocationManagerDelegate>

@property (nonatomic, retain) CLLocationManager* locationManager;


@end

PSCoordinates.m

#import "PSCoordinates.h"

@implementation PSCoordinates

- (id) init {
    self = [super init];

    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        if ([CLLocationManager locationServicesEnabled])
        {
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            self.locationManager.distanceFilter = 100.0f;
            NSLog(@"PSCoordinates init");
            [self.locationManager startUpdatingLocation];
        }
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"Géolocalisation : %@",[newLocation description]);
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    NSLog(@"Géolocalisation (erreur) : %@",[error description]);

}


@end

我打电话给他

PSCoordinates * coordinates = [[PSCoordinates alloc] init];

按下按钮时init正在工作,因为我可以看到NSLog PSCoordinates init

我发现人们遇到同样问题的其他话题,但答案都没有解决。

非常感谢您的帮助。

ios delegates cllocationmanager
1个回答
13
投票

在您的班级中将“PSCoordinates * coordinates”设为全局。它会工作:)

© www.soinside.com 2019 - 2024. All rights reserved.