在以下函数中,我使用了一个块。但是当我调用这个函数时,它甚至在块执行之前就返回了。我理解 Block 依次使用线程并单独执行,以便该函数不会等待它返回。但是,是否有任何其他方法可以让函数执行等待,或者有任何其他方法可以在不使用块本身的情况下实现该块的功能?
-(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;
}
首先,我建议重新考虑你的设计。不要从此方法返回 zipCode 值,而是调用completionHandler 中的其他方法(创建协议/委托或其他方法)。这reverseGeocodeLocation::
方法可能需要一些时间,并且您不想暂停等待结果的主线程的执行。
如果您确实想阻止,您可以考虑使用(滥用?)dispatch_semaphore_t
。将其初始化为 0 并dispatch_semaphore_wait
致电后reverseGeocodeLocation::
。在completionHandler中用以下信号通知它dispatch_semaphore_signal
.
更多信息:使用调度信号量来调节有限资源的使用 http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW24
编辑:像其他人建议的那样,使用 __block 限定符声明 zipCode
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)