Pra*_*mar 5 iphone objective-c objective-c-blocks ios5
在以下函数中,我使用了一个块.但是当我调用这个函数时,它甚至在块执行之前就会返回.我知道Block inturn使用线程并单独执行,因此函数不会等待它返回.但是,有没有其他方法可以使函数执行等待,或任何其他方式来实现此块的功能而不使用块本身?
-(int)findCurrentZip
{
CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:[self findCurrentLatitude]
longitude:[self findCurrentLongitude]];
int zipcode;
self.myGeocoder = [[CLGeocoder alloc] init];
[self.myGeocoder
reverseGeocodeLocation:userLocation
completionHandler: (id)^(NSArray *placemarks, NSError *error) {
if (error == nil && [placemarks count] > 0)
{
NSLog(@"Placemarks: %@",placemarks);
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"Country = %@", placemark.country);
NSLog(@"Postal Code = %@", placemark.postalCode);
zipcode = (int)placemark.postalCode;
NSLog(@"Locality = %@", placemark.locality);
NSLog(@"Country%@",[placemarks lastObject]);
}
else if (error == nil && [placemarks count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
}
}];
return zipcode;
}
Run Code Online (Sandbox Code Playgroud)
首先,我建议重新考虑你的设计.而不是从此方法返回zipCode值,而是调用completionHandler中的其他方法(创建协议/委托或其他).该reverseGeocodeLocation::方法可能需要一些时间,您不希望暂停执行等待结果的主线程.
如果你确实想要阻止,你可以考虑使用(滥用?)a dispatch_semaphore_t.将其初始化为0并dispatch_semaphore_wait在调用之后reverseGeocodeLocation::.在completionHandler信号中用它dispatch_semaphore_signal.
编辑:和其他建议一样,使用__block限定符声明zipCode
| 归档时间: |
|
| 查看次数: |
5729 次 |
| 最近记录: |