我需要知道我的用户来自哪里,所以我做了一个小的单例对象,它获取坐标并使用mapkit来获取我需要的国家代码。
下面是我的头文件:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#define TW_GEO_CODER_CHANGED_STATE @"TW_GEO_CODER_CHANGED_STATE"
@interface TWGeoCoder : NSObject <CLLocationManagerDelegate, MKReverseGeocoderDelegate>
{
CLLocationManager *locationManager;
MKReverseGeocoder *geoCoder;
NSString *currentCountryIsoCode;
}
+ (TWGeoCoder*) sharedTWGeoCoder;
-(void) startGeoCoder;
-(void) stopGeoCoder;
@property (nonatomic, retain) NSString *currentCountryIsoCode;
@end以及实现方法:
#import "TWGeoCoder.h"
@implementation TWGeoCoder
static TWGeoCoder* _singleton;
+ (TWGeoCoder*) sharedTWGeoCoder
{
@synchronized([TWGeoCoder class])
{
if (_singleton == nil)
{
_singleton = [[TWGeoCoder alloc] init];
}
}
return _singleton;
}
- (void)startGeoCoder
{
if (locationManager == nil)
{
locationManager = [[CLLocationManager alloc] init];
}
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.purpose = NSLocalizedString(@"#LocalizationPurpose",nil);
[locationManager startUpdatingLocation];
}
- (void) stopGeoCoder
{
if (geoCoder != nil)
{
[geoCoder cancel];
[geoCoder release];
geoCoder = nil;
}
if (locationManager != nil)
{
[locationManager stopUpdatingLocation];
[locationManager release];
locationManager = nil;
}
}
#pragma mark -
#pragma mark locationManager Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (geoCoder == nil)
{
geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];
}
geoCoder.delegate = self;
[geoCoder start];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"locationManager:%@ didFailWithError:%@", manager, error);
[self stopGeoCoder];
}
#pragma mark -
#pragma mark reverseGeocoder Delegate
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
self.currentCountryIsoCode = placemark.countryCode;
[[NSNotificationCenter defaultCenter] postNotificationName:TW_GEO_CODER_CHANGED_STATE
object:self];
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);
[self stopGeoCoder];
}
#pragma mark -
#pragma mark Synthesizes
@synthesize currentCountryIsoCode;
@end嗯,调用stopGeoCoder方法会使我的应用程序崩溃,即使是通过performSelectorOnMainThread调用它也是如此…
问题出在以下几行中:
if (geoCoder != nil)
{
[geoCoder cancel];
[geoCoder release];
geoCoder = nil;
}当我试图发布它的时候,MKReverseGeocoder似乎变得非常生气!我只在"didFail“方法上得到崩溃。实际上,当它找到placemark时,另一个类将收到通知,做一些事情并调用stopGeocoder和...它不会崩溃!见鬼?
发布于 2011-07-22 15:56:21
你应该参考堆栈溢出中的另一个帖子来解决这个问题:
https://stackoverflow.com/questions/5705282
复制相似问题