1

我对以下代码有“问题”。错误消息是:单击注释 #4 的标注时,应用程序试图在目标 UINavigationController:0x10b82bbf0 上推送一个 nil 视图控制器。如何在不出现此错误的情况下打开警报视图?

//Callout button action

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view       
calloutAccessoryControlTapped:(UIControl *)control{
  if ([view.annotation isKindOfClass:[Annotation class]])
  {
    Annotation *myAnn = (Annotation *)view.annotation;
    id vcToPush = nil;
    if ([[myAnn title] isEqualToString:@"1. Annotation one"]){
        vcToPush = [[FirstViewController alloc]init];
    }
    if ([[myAnn title] isEqualToString:@"2. Annotation two"]){
        vcToPush = [[SecondViewController alloc]init];
    }
    if ([[myAnn title] isEqualToString:@"3. Annotation three"]){
        vcToPush = [[ThirdViewController alloc]init];
    }
    if ([[myAnn title] isEqualToString:@"4. Annotation four"]){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Fourth annotation" message:@"Message" delegate:nil cancelButtonTitle:@"OK" 
  otherButtonTitles:nil];
        [alertView show];
    }

    [self.navigationController pushViewController:vcToPush animated:YES];
  }
}


//Custom callout

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)myAnn {
//Current location blue dot
if ([myAnn isKindOfClass:[MKUserLocation class]])
{
    ((MKUserLocation *)myAnn).title = @"My position";
    return nil;
}//
MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"pinView"];
if (!pinView) {
    pinView = [[MKPinAnnotationView alloc] initWithAnnotation:myAnn reuseIdentifier:@"pinView"];
    pinView.pinColor = MKPinAnnotationColorRed;
    pinView.canShowCallout = YES;
    pinView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
}
else
{
    pinView.annotation = myAnn;
}
return pinView;
}

谢谢!

4

1 回答 1

0

在 if 块中

if ([[myAnn title] isEqualToString:@"4. Annotation four"]){

vcToPush没有初始化。因此 is 具有调用方法之前的值(nil在这种情况下)。

我假设您只想在 #4 的情况下显示警报。在这种情况下,在 if 块中添加一个 return:

if ([[myAnn title] isEqualToString:@"4. Annotation four"]){
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Fourth annotation" message:@"Message" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    return;
}
于 2014-07-18T10:48:24.837 回答