我想获取当前位置的地址并将其设置为注释的标题。但它没有用。我认为这是因为阻塞,但我不知道如何修复它。任何帮助将不胜感激。最相关的代码如下:
WhereAmIAnotation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>
@interface WhereAmIAnnotation : NSObject <MKAnnotation>
{
CLLocation *myLocation;
NSString *addr;
}
@property (nonatomic, retain) CLLocation *myLocation;
@property (nonatomic, copy) NSString *addr;
@end
WhereAmIAnnotation.m
#import "WhereAmIAnnotation.h"
@implementation WhereAmIAnnotation
@synthesize myLocation, addr;
- (CLLocationCoordinate2D)coordinate;
{
return self.myLocation.coordinate;
}
- (NSString *)title
{
return self.addr;
}
@end
MapViewController.m
- (IBAction)gotoCurrentLocation{
self.mapView.showsUserLocation = YES;//a bar button linked with this action
}
- (void)mapViewMKMapView *)mapView didUpdateUserLocationMKUserLocation *)userLocation
{
CLLocation *currentLocation = userLocation.location;
MKCoordinateRegion newRegion;
newRegion.center = currentLocation.coordinate;
newRegion.span.latitudeDelta = 0.02;
newRegion.span.longitudeDelta = 0.02;
[self.mapView setRegion:newRegion animated:YES];
WhereAmIAnnotation *whereAmIAnnotation = [[WhereAmIAnnotation alloc] init];
whereAmIAnnotation.myLocation = currentLocation;
whereAmIAnnotation.addr = [self addrAtLocation:currentLocation];
[self.mapView addAnnotation:whereAmIAnnotation];
self.mapView.showsUserLocation = NO;
}
- (NSString *)addrAtLocationCLLocation *)location{
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *topResult = [placemark objectAtIndex:0];
self.addr = [NSString stringWithFormat"%@ %@ %@ %@", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare];
}];
return self.addr;
}
我应该实现这个方法
- (MKAnnotationView *)mapViewMKMapView *)theMapView viewForAnnotationid )annotation{}
抱歉这个愚蠢的问题!
您在异步 block 内修改地址时返回地址。您应该将 return 移到 block 内,或者创建一个协议(protocol)来处理将此信息传递回调用者。
将 block 更改为:
- (void)addrAtLocationCLLocation *)location{
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemark, NSError *error) {
CLPlacemark *topResult = [placemark objectAtIndex:0];
whereAmIAnnotation.addr = [NSString stringWithFormat"%@ %@ %@ %@", topResult.country, topResult.locality, topResult.subLocality, topResult.thoroughfare];
}];
}
然后将 whereAmIAnnotation
设为成员变量。您了解为什么这可以解决您的问题吗?
关于iphone - 将注解的标题设置为当前地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633957/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |