CLLocationManager没有在NSObject中调用委托

Nic*_*Roy 5 delegates cllocationmanager ios

我正在尝试创建一个帮助程序类,以便轻松地在任何其他类中获取手机的坐标.我已经按照一个教程UIViewController实现了<CLLocationManagerDelegate>它的工作.我尝试在一个简单的方法中做同样的事情NSObject,但后来我的代表再也没有被调用.

这是我的代码:

PSCoordinates.h

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

@interface PSCoordinates : NSObject <CLLocationManagerDelegate>

@property (nonatomic, retain) CLLocationManager* locationManager;


@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我打电话给他

PSCoordinates * coordinates = [[PSCoordinates alloc] init];
Run Code Online (Sandbox Code Playgroud)

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

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

非常感谢您的帮助.

Aug*_*P A 13

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

  • @ h.kishan因为ARC已为您的项目启用,并且您将变量'coordinates'声明为local.编译器将在下一次找到对象的范围结束时向该实例添加一条释放消息.因此,您的实例已经发布并且不再存在.所以你的代表不会工作.将变量声明为全局变量时,它将一直存在,直到其父类存在.所以你的代表会被召唤. (4认同)