使用块中的数据初始化属性

时间:2014-09-08 10:59:58

标签: ios objective-c-blocks

我想用块中的变量初始化CLLocationCoordinate2D属性。

在我的company.h文件中:

@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。

我怎样才能让它发挥作用?

1 个答案:

答案 0 :(得分:0)

这是因为块中的语句在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);
                 }
             }
     ];
}