Ios 使用块中的数据初始化特性
我想用块中的变量初始化CLLocationCoordinate2D属性 在my company.h文件中:Ios 使用块中的数据初始化特性,ios,objective-c-blocks,Ios,Objective C Blocks,我想用块中的变量初始化CLLocationCoordinate2D属性 在my company.h文件中: @property CLLocationCoordinate2D cllocation; 在我的company.m文件中 NSString *addressComplete = [NSString stringWithFormat:@"%@ %d %@", address,(int) plz, place]; [self convertAddress:addressComplet
@property CLLocationCoordinate2D cllocation;
在我的company.m文件中
NSString *addressComplete = [NSString stringWithFormat:@"%@ %d %@", address,(int) plz, place];
[self convertAddress:addressComplete];
-(void)convertAddress:(NSString*) address
{
NSString *location = address;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
_cllocation.longitude = placemark.location.coordinate.longitude;
_cllocation.latitude = placemark.location.coordinate.latitude;
}
}
];
NSLog(@"longitude: %f", _cllocation.longitude);
}
NSLog显示_cllocation为0.0000
我如何才能让它工作?这是因为块中的语句是在NSLog语句之后执行的。您正在分配前打印结果。在块内移动NSLog
-(void)convertAddress:(NSString*) address
{
NSString *location = address;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
_cllocation.longitude = placemark.location.coordinate.longitude;
_cllocation.latitude = placemark.location.coordinate.latitude;
NSLog(@"longitude: %f", _cllocation.longitude);
}
}
];
}
这是因为block中的语句是在NSLog语句之后执行的。这种问题在这个论坛上被多次提出…:(关于块的内容和块的外部环境之间的连接:简单地说,
NSLog(…)
是在块运行之前执行的。我建议将方法重命名为“startConvertingAddress”因为它就是这样做的。它会开始转换,但只会在一段时间后完成。顺便说一句,您的代码不是线程安全的。_cllocation.longitude将在未知线程上设置。