这是我的 AppDelegate 类中的代码
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = 1000; // 1 Km
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
[locationManager startUpdatingLocation];
}
这是我在 AppDelegate 类中的委托(delegate)方法
//This is the delegate method for CoreLocation
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
//printf("AppDelegate latitude %+.6f, longitude %+.6f\n", newLocation.coordinate.latitude, newLocation.coordinate.longitude);
}
它可以在 3.0、3.1、3.1.3 中工作,但在 4.0 模拟器和设备中都不起作用。
原因是什么?
最佳答案
我也遇到过类似的错误,现在已经解决了。问题是在本地声明 locationManager 变量。将其声明为类变量,并确保它直接保留或通过属性保留(如果使用 ARC,则为强保留)。这样就解决了问题!问题是 de locationManager 变量被释放并且从未更新委托(delegate)。代码如下:
.h 文件:
#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface MapViewController : UIViewController <MKMapViewDelegate, CLLocationManagerDelegate> {
@private
MKMapView *_mapView;
CLLocationManager *_locationManager;
}
@property(nonatomic, strong) CLLocationManager *locationManager;
@end
.m 文件:
self.locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[_locationManager startUpdatingLocation];
希望对您有所帮助。
关于iphone - 为什么 CLLocationManager 委托(delegate)在 iPhone SDK 4.0 中没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3058927/