【问题标题】:CLLocationManager not calling delegate in an NSObjectCLLocationManager 没有在 NSObject 中调用委托
【发布时间】:2013-05-07 14:32:25
【问题描述】:

我正在尝试创建一个帮助类来轻松获取手机在任何其他类中的坐标。我遵循了一个教程,其中 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];

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

我发现有同样问题的人的其他主题,但没有一个答案能解决它。

非常感谢您的帮助。

【问题讨论】:

    标签: ios delegates cllocationmanager


    【解决方案1】:

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

    【讨论】:

    • 你是老板!非常感谢:)
    • 谢谢它真的帮助了我,但是你知道为什么会这样吗?
    • @h.kishan 因为为您的项目启用了 ARC,并且您将变量“坐标”声明为本地变量。编译器将在下一个发现对象范围结束的时刻向该实例添加释放消息。因此,您的实例已经发布并且不再存在。所以你的代表不会工作。当您将变量声明为全局变量时,它将一直存在,直到其父类存在为止。所以你的代表会被叫到。
    • 这就是答案!太棒了:)
    • @AugustinePA 您如何在 Swift 2.0 中使其全球化,有什么想法吗?
    猜你喜欢
    • 2013-12-03
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2011-04-13
    • 2011-11-29
    相关资源
    最近更新 更多