在块中分配NSString变量时出错

时间:2011-10-12 15:00:39

标签: ios objective-c-blocks

    - (NSString *) geocodeAddressFromCoordinate:(CLLocationCoordinate2D)coordinate
    {
        CLLocation *location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
        __block NSMutableString * address = [NSMutableString string];  
        geocoder = [[CLGeocoder alloc]init];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) 
         {
             if (error) {     
                 NSLog(@"%@", [error localizedDescription]);
                 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No results were found" message:@"Try another search" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
                 alert.show;
                 return;
             }
             if ([placemarks count]>0) 
             {   
                 NSLog([placemarks description]);
                 CLPlacemark *placemark = [placemarks objectAtIndex:0];
                 NSLog(placemark.locality);
//This line makes an error
                 [address initWithString:placemark.locality];**
             }
         }];
        return address;
    }

发生以下运行时错误:

  

*由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* 初始化方法   -initWithCharactersNoCopy:length:freeWhenDone:无法发送到类__NSCFString的抽象对象:创建一个具体的实例!'

4 个答案:

答案 0 :(得分:3)

你不应该在没有匹配的alloc的情况下调用'initWithString:'。看起来更像你想要的是[address setString:placemark.locality]

答案 1 :(得分:3)

您已使用此行address初始化[NSMutableString string];,因此您对[address initWithString:placemark.locality];的调用正在尝试初始化已初始化的对象。

改变这个:

[address initWithString:placemark.locality];

要:

[address setString:placemark.locality];

NSString Class Reference
NSMutableString Class Reference

答案 2 :(得分:2)

[address initWithString:placemark.locality];

应该更像是:

address = placemark.locality;

[address appendString:placemark.locality];

取决于你想要完成什么。

答案 3 :(得分:1)

此时,您的字符串已经初始化,[NSMutableString string]是一个方便的方法,它必须返回[[[NSMutableString alloc] init] autorelease]。您正在尝试重新启动一个已经存在的对象,这很糟糕。

将该行更改为[address appendString:placemark.locality];