我正在尝试了解崩溃日志。当我尝试执行CLLocationDistance
方法distanceFromLocation
时会发生这种情况。为了得到两个我需要进行地理编码的位置,但我需要一个块,所以我可以拥有这两个实例变量。所以我将它指向一个带参数的方法:
- (void)geoCodeSetup:(NSArray *)placemarks :(NSError *)error andIdentifier:(NSString *)string {
CLLocation *location1;
CLLocation *location2;
if ([string isEqualToString:@"Origin"]) {
if (!error) {
CLPlacemark *place = [placemarks objectAtIndex:0];
CLLocation *location = place.location;
location1 = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
} else {
NSString *string = [NSString stringWithFormat:@"%@ - also make sure you have inputted a valid city", [error localizedDescription]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:string delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
if ([string isEqualToString:@"Destination"]) {
if (!error) {
CLPlacemark *place = [placemarks objectAtIndex:0];
CLLocation *location = place.location;
location2 = [[CLLocation alloc] initWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
} else {
NSString *string = [NSString stringWithFormat:@"%@ - also make sure you have inputted a valid city", [error localizedDescription]];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:string delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alert show];
}
}
CLLocationDistance distanceM = [location1 distanceFromLocation:location2];
[metreDistance setText:[NSString stringWithFormat:@"%f", distanceM]];
}
- (IBAction)calculateDistance {
[textFieldDestination resignFirstResponder];
NSString *origin = [textFieldOrigin text];
if (origin) {
CLGeocoder *geoCode = [[CLGeocoder alloc] init];
[geoCode geocodeAddressString:origin completionHandler: ^(NSArray *placemarks, NSError *error) {
NSArray *p1 = placemarks;
NSError *e1 = error;
[p1 retain];
[e1 retain];
[self geoCodeSetup:p1 :e1 andIdentifier:@"Origin"];
}];
}
NSString *destination = [textFieldDestination text];
if (destination) {
CLGeocoder *geoCode2 = [[CLGeocoder alloc] init];
[geoCode2 geocodeAddressString:destination completionHandler:^(NSArray *placemarks, NSError *error) {
NSArray *p2 = placemarks;
NSError *e2 = error;
[p2 retain];
[e2 retain];
[self geoCodeSetup:p2 :e2 andIdentifier:@"Destination"];
}];
}
它在distanceFromLocation部分崩溃/给出EXC_BAD_ACCESS (code =EXC_ARM_DA_ALIGN, address=.....etc....)
。我附上了崩溃日志的截图。
可能导致此问题的原因以及如何解决?
答案 0 :(得分:2)
我认为没有设置location1或location2,因为你确实把它包装进了
if ([string isEqualToString:@"Origin"]) {
if (!error) {
您可以通过将第2行和第3行链接到:
来避免崩溃CLLocation *location1 = nil;
CLLocation *location2 = nil;
也许您还需要更改行:
CLLocationDistance distanceM = [location1 distanceFromLocation:location2];
// change to
CLLocationDistance distanceM;
if(location1 && location2) {
distanceM = [location1 distanceFromLocation:location2];
}
我认为您使用至少一个NULL参数或对象运行distanceFromLocation:
。