我试图将地标位置从CLGeocoder传递到名为cityLabel的另一个类UILabel。 CLGeocoder的类名为WXManager,mainViewController名为WXController。我已经尝试了各种方法使它工作,但我根本无法将城市名称传递给cityLabel。
WXManager.h
@class WXManager;
@protocol WXManagerDelegate <NSObject>
- (void)WXManagerDidGeocodeCityName:(NSString *)cityName;
@end
@interface WXManager : NSObject <CLLocationManagerDelegate>
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
@end
WXManager.m
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
if (self.isFirstUpdate) {
self.isFirstUpdate = NO;
return;
}
CLLocation *location = [locations lastObject];
if (location.horizontalAccuracy > 0) {
self.currentLocation = location;
[self.locationManager stopUpdatingLocation];}
CLGeocoder *fgeo = [[CLGeocoder alloc] init];
// Reverse Geocode a CLLocation to a CLPlacemark
[fgeo reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error){
if(!error){
for(CLPlacemark *placemark in placemarks){
self.cityName = [placemark locality];
[self.customDelegate WXManagerDidGeocodeCityName:self.cityName];
NSLog(@"city is %@",cityName); }
} else {
NSLog(@"There was a reverse geocoding error\n%@",
[error localizedDescription]);
}
}
];
}
WXController.h
@interface WXController : UIViewController
<WXManagerDelegate>
- (void)WXManagerDidGeocodeCityName:(NSString *)cityName;
@end
最后在WXController.m中问题似乎是,我的方法WXManagerDidGeocodeCityName不会被调用。我不知道哪里错了。有谁知道怎么让这个方法被调用?
WXManager *cityName = [[WXManager alloc] init];
cityName.customDelegate = self;
#pragma mark - Custom Delegate Method
- (void)WXManagerDidGeocodeCityName:(NSString *)cityName
{
[self.cityLabel setText:cityName];
NSLog(@"cityName is %@", cityName);
NSLog(@"DidGetCalled");
}
日志没有被调用,所以必须在某处丢失。
答案 0 :(得分:2)
试试这个:
<强> WXManager.h 强>
@class WXManager;
@protocol WXManagerDelegate <NSObject>
- (void)WXManagerDidGeocodeCityName:(NSString *)cityName;
@end
@interface WXManager : NSObject <CLLocationManagerDelegate> {
id <WXManagerDelegate> customDelegate;
}
@property (retain)id customDelegate;
@end
<强> WXController.h 强>
@interface WXController : UIViewController <WXManagerDelegate>
//- (void)WXManagerDidGeocodeCityName:(NSString *)cityName;
@end
答案 1 :(得分:1)
在WXManager.m中,您需要初始化CLLocationManager:
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
一切都会好起来的
答案 2 :(得分:1)
我猜测cityName
是weak
,或者有一个自定义的setter / getter来清除/忽略正确的值。
编辑以澄清:
我在这里谈论你的cityName
:
WXManager *cityName = [[WXManager alloc] init];
cityName.customDelegate = self;
我假设稍后会为其分配一些属性self.cityName
。
如果不这样做,那么在完成处理程序运行之前,self.customDelegate
将变为nil
。
答案 3 :(得分:1)
该方法未被调用?或变量cityName等于nil?
如果是第一个 - 寻找你的代表可能是等于零。 如果第二个 - CLGeocoder工作不正确。
一般是漫步调试器。看看变量。快速了解一切。
答案 4 :(得分:0)
在WXManager.m中,您需要初始化CLLocationManager:
self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; [self.locationManager startUpdatingLocation];
一切都会好起来的