0
我需要知道我的用戶來自哪裏,所以我做了一個單獨的對象,它獲取座標並使用mapkit獲取我需要的國家代碼。發佈MKReverseGeocoder會導致我的應用崩潰!
這是我的頭文件:
#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」方法中發生崩潰。 實際上,當它發現地標時,另一個類將得到通知,執行某些操作並調用stopGeocoder,並且它不會崩潰! WTF?