【发布时间】:2013-08-09 16:44:55
【问题描述】:
在以下代码块中,第一个方法调用第二个方法,该方法应返回地理编码过程的结果:
- (void)foo {
CLPlacemark *currentMark = [self reverseGeocodeLocation:locationManager.location];
}
- (CLPlacemark *)reverseGeocodeLocation:(CLLocation *)location {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
__block CLPlacemark *placeMark;
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (!error) {
if ([placemarks firstObject])
placeMark = [placemarks firstObject];
}
}];
return placeMark;
}
但是,由于程序的执行,在继续之前不会等待地理编码完成(因此完成块),总是存在placeMark 变量将在地理编码过程完成之前未经实例化返回的危险,并且调用完成块。在向 Web 服务发出 HTTP 请求时,我遇到了同样的困境,但结果在不确定的时间内不会返回。
到目前为止,我看到的唯一解决方案是将foo 中的所有代码嵌套在地理编码器的完成块中,这很快就会变得非常丑陋且难以维护。
将foo 中的currentMark 变量设置为第二个方法的完成块的结果而不将其嵌套在块中的最佳方法是什么?
【问题讨论】:
标签: ios objective-c oop objective-c-blocks