我有一个前向gecodoing方法。我想将结果保存在变量中,以便我可以在viewDidLoad中使用它。
- (void)getGeoInformations
{
NSLog(@"Begin");
__block NSString *returnAddress = @"";
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder geocodeAddressString:@"Isartor" completionHandler:^(NSArray* placemarks, NSError* error){
if(error) {
NSLog(@"Error");
return;
}
CLPlacemark *placemark = [placemarks lastObject];
NSArray *lines = placemark.addressDictionary[ @"FormattedAddressLines"];
//addressString = [lines componentsJoinedByString:@"\n"];
NSString *str_latitude = [NSString stringWithFormat: @"%f", placemark.location.coordinate.latitude];
NSString *str_longitude = [NSString stringWithFormat: @"%f", placemark.location.coordinate.longitude];
returnAddress = [NSString stringWithFormat:@" %@, %@, %@",
lines,
str_latitude, str_longitude];
NSLog(returnAddress);
NSLog(@"Ende");
[self loadGeoInformations:returnAddress];
}];
}
经过www研究,我知道,这是一个异步调用,我必须使用回调。
-(void)loadGeoInformations:(NSString*)returnAddress {
}
我已尝试过几件事来存储 returnAddress ,但没有成功..
如何保存结果?
谢谢你。
答案 0 :(得分:0)
使用实例变量。在.m文件的顶部声明实例var NSString:
@interface YourFileHere {
NSString *_returnAddress;
}
然后,稍后当您调用传递地址的方法时,可以将其保存到实例变量中以便以后使用。
-(void)loadGeoInformations:(NSString*)returnAddress {
_returnAddress = returnAddress;
}
以下是包含日志和评论的完整代码,其中显示了事情将如何发生:
- (void)viewDidLoad {
[super viewDidLoad];
// #1 - This is called first
NSLog(@"Calling getGeoInformations in view did load.");
[self getGeoInformations];
}
- (void)getGeoInformations {
// #2 - This will be called during view did load.
NSLog(@"Inside getGeoInformations");
CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder geocodeAddressString:@"Isartor" completionHandler:^(NSArray* placemarks, NSError* error){
// This is called later, at some point after view did load is called.
NSLog(@"Inside completionHandler.");
if(error) {
NSLog(@"Error");
return;
}
CLPlacemark *placemark = [placemarks lastObject];
NSArray *lines = placemark.addressDictionary[@"FormattedAddressLines"];
NSString *str_latitude = [NSString stringWithFormat: @"%f", placemark.location.coordinate.latitude];
NSString *str_longitude = [NSString stringWithFormat: @"%f", placemark.location.coordinate.longitude];
NSString *returnAddress = [NSString stringWithFormat:@" %@, %@, %@", lines, str_latitude, str_longitude];
// #4 - Now we have the return address, so we can pass it to the load method.
[self loadGeoInformations:returnAddress];
}];
// #3 - Anything here will be called during view did load, but BEFORE the completion handler of the geocoding process is called.
NSLog(@"This is called third.");
}
- (void)loadGeoInformations:(NSString*)returnAddress {
// #5 - this will be called last, some time after view did load is done.
_returnAddress = returnAddress;
NSLog(@"Inside load geo informations with return address: %@", _returnAddress);
}