开发者

Error when assigning NSString variable in a block

    - (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;
             开发者_如何学C    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;
    }

Got following runtime error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* initialization method -initWithCharactersNoCopy:length:freeWhenDone: cannot be sent to an abstract object of class __NSCFString: Create a concrete instance!'


You should never call 'initWithString:' without a matching alloc. Looks more like what you want is [address setString:placemark.locality]


You have already initialized address with this line [NSMutableString string]; so your call to [address initWithString:placemark.locality]; is trying to initialize an already initialized object.

Change this:

[address initWithString:placemark.locality];

To:

[address setString:placemark.locality];

NSString Class Reference
NSMutableString Class Reference


[address initWithString:placemark.locality];

should be something more like:

address = placemark.locality;

or

[address appendString:placemark.locality];

depending on what yu are trying to accomplish.


At this point, your string is already initialized, [NSMutableString string] is a convenience method which essential returns [[[NSMutableString alloc] init] autorelease]. You are trying to re init an already inited object, which is bad.

Change that line to [address appendString:placemark.locality];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜