[英]Adding City and State Information to MKAnnotation Using CLGeocoder
我正在尝试将城市和州信息添加到MKAnnotation中,但是在将数据添加到注释中之前已清除了数据。 这是我当前的代码(为简单起见,仅显示需要关注的部分):
在实施中:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
[self setCity:[placemark locality] andState:[placemark administrativeArea]];
}];
NSLog(@"Location 1: %@, %@", city, state);
MapPoint *mp = [[MapPoint alloc] initWithCoordinate:[newLocation coordinate]
title:[locationTitleField text]
date:[dateFormat stringFromDate:today]];
[mapView addAnnotation:mp];
}
- (void)setCity:(NSString *)c andState:(NSString *)s
{
[self setCity:c];
[city retain];
[self setState:s];
[state retain];
NSLog(@"Location 2: %@, %@", city, state);
}
在界面中:
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate>
{
CLLocationManager *locationManager;
IBOutlet MKMapView *mapView;
NSString *city;
NSString *state;
}
@property (strong, nonatomic) IBOutlet UIWindow *window;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *state;
- (void)setCity:(NSString *)c andState:(NSString *)s;
@end
位置1打印(null),(null),而位置2打印加州旧金山。 为什么在我可以在批注中使用它们之前从这些属性中删除数据?
非常感谢...
位置1为空的原因是,反向地理编码器在运行时尚未完成。 在你的一切completionHandler
地址解析器结束后会发生。 您在位置1的日志语句不是该completionHandler
一部分,而是在调用反向地理编码后立即执行。 最终结果是在调用setCity:andState:
之前发生了日志调用。
更新资料
您需要在completionHandler
块中设置注释。 出现在块中的代码在顺序和时间上晚于locationManager:didUpdateToLocation:fromLocation:
消息实现的其余部分。 您可能希望阅读有关Apple文档中的内容或搜索Internet。
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
[self setCity:[placemark locality] andState:[placemark administrativeArea]];
MapPoint *mp = [[MapPoint alloc] initWithCoordinate:[newLocation coordinate]
title:[locationTitleField text]
date:[dateFormat stringFromDate:today]];
[mapView addAnnotation:mp];
}];
}
结束更新
另外,看起来您好像并没有很好地使用属性。 由于您具有city
和state
属性,因此不需要city
和state
实例变量。
尝试这样更改它:
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate>
{
CLLocationManager *locationManager;
IBOutlet MKMapView *mapView;
}
在实施中:
@synthesize city, state
...
- (void)setCity:(NSString *)c andState:(NSString *)s
{
[self setCity:c];
[self setState:s];
NSLog(@"Location 2: %@, %@", city, state);
}
您不需要额外的keep语句,因为该属性复制了值。 您还必须确保调用self.city
和self.state
来获取值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.