5
我想創建一個幫手類,以輕鬆獲取任何其他類中的電話座標。我遵循教程,其中UIViewController
實施<CLLocationManagerDelegate>
,它的工作。我試圖在一個簡單的NSObject
中做同樣的事情,但之後我的委託不再被調用。CLLocationManager不調用委託在一個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
。
我發現有同樣問題的人的其他主題,但沒有答案解決它。
您的幫助將非常感激。
你是老闆!非常感謝:) – 2013-05-07 15:08:08
感謝它真的幫助我,但你知道它爲什麼如此嗎? – 2014-01-23 06:32:57
@ h.kishan由於您的項目已啓用ARC,並且您正在將變量「座標」聲明爲本地。編譯器會在發現對象的作用域結束時立即向此實例添加一條釋放消息。所以,你的實例已經被釋放並且不再存在。所以你的代表不會工作。 當您將變量聲明爲全局變量時,它將一直存在,直到其父類存在。所以你的委託會被調用。 – 2014-01-24 18:45:08