2012-06-22 2 views
0

У меня есть этот код:Аннотации в MapView

-(void)handleLongPressGesture:(UIGestureRecognizer*)sender { 

NSNumber* existingpoints = [[NSNumber alloc]init]; 


existingpoints =[NSNumber numberWithInt:0]; 


// This is important if you only want to receive one tap and hold event 
if (sender.state == UIGestureRecognizerStateEnded) 
{ 
    [self.mapView removeGestureRecognizer:sender]; 
} 
else { 

    do { 
     int z = 1; 
     existingpoints =[NSNumber numberWithInt:z]; 

     // Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map 
     CGPoint point = [sender locationInView:self.mapView]; 
     CLLocationCoordinate2D locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView]; 
     // Then all you have to do is create the annotation and add it to the map 

     MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init]; annotationPoint.coordinate = locCoord; 



     NSString *latitude = [[NSString alloc] initWithFormat:@"%f",locCoord.latitude]; 


     NSString *longitude = [[NSString alloc] initWithFormat:@"%f", locCoord.longitude]; 


     annotationPoint.title = @"Event"; 
     annotationPoint.subtitle = [NSString stringWithFormat:@"%@ & %@", latitude, longitude]; 

     [mapView addAnnotation:annotationPoint]; 


     [[NSUserDefaults standardUserDefaults]setObject:latitude forKey:@"FolderLatitude"]; 
     [[NSUserDefaults standardUserDefaults]setObject:longitude forKey:@"FolderLongitude"]; 


    } while ([existingpoints intValue] == 0); 

     } 
} 

... но проблема в том, что когда я держу, а затем перетащить больше чем один штырь добавляется. Я хочу добавить только один вывод. Поэтому я попробовал метод do, но он не работает. Я не могу понять, потому что, когда я выполнял код, я возвращаю значение NSNumber равным 1, а while говорит = 0 для запуска кода.

Пожалуйста, помогите !!

ответ

0

Ваш текущий код подвержен большому количеству утечек памяти. Например:

NSNumber* existingpoints = [[NSNumber alloc] init]; 
existingpoints = [NSNumber numberWithInt:0]; 

подтекает, потому что вы оставите первый экземпляр existingpoints с сохраняют значение 1, а не освобождая его в любом месте. Если вы не используете ARC. Вы можете оптимизировать код выше только с одной командой:

NSNumber* existingpoints = [NSNumber numberWithInt:0]; 

И сохранить его, если вам нужно сохранить его где-нибудь (но я верю, что это не так).

Анализ кода, я бы рекомендовал НЕ использовать существующие точки как NSNumber. Вместо этого используйте NSInteger (который не является объектом, а всего лишь typedef до long).

Вот мой переписан код:

-(void)handleLongPressGesture:(UIGestureRecognizer*)sender { 
    NSInteger existingpoints = 0; 

    // This is important if you only want to receive one tap and hold event 
    if (sender.state == UIGestureRecognizerStateEnded) { 
     [self.mapView removeGestureRecognizer:sender]; 
    } 
    else { 
     do { 
      int z = 1; 
      existingpoints = z; 

      // Here we get the CGPoint for the touch and convert it to latitude and longitude coordinates to display on the map 
      CGPoint point = [sender locationInView:self.mapView]; 
      CLLocationCoordinate2D locCoord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView]; 

      // Then all you have to do is create the annotation and add it to the map 
      MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init]; 
      annotationPoint.coordinate = locCoord; 

      NSString *latitude = [NSString stringWithFormat:@"%f",locCoord.latitude]; 
      NSString *longitude = [NSString stringWithFormat:@"%f", locCoord.longitude]; 

      annotationPoint.title = @"Event"; 
      annotationPoint.subtitle = [NSString stringWithFormat:@"%@ & %@", latitude, longitude]; 

      [mapView addAnnotation:annotationPoint]; 

      [[NSUserDefaults standardUserDefaults] setObject:latitude forKey:@"FolderLatitude"]; 
      [[NSUserDefaults standardUserDefaults] setObject:longitude forKey:@"FolderLongitude"]; 

      [annotationPoint release]; // Remove this if you're using ARC. 
     } while (existingpoints == 0); 
    } 
} 

Обратите внимание, что я также изменил код для создания latitude и longitude для, чтобы не создавать каких-либо утечек памяти при использовании ARC.

EDIT: Дальнейший анализ вашего кода, я не понимаю, почему этот метод будет удалять сразу два контакта. Может быть, вы можете проверить, не вызван ли ваш метод дважды?

Подробнее: Почему у вас есть цикл do/while, если вы просто хотите, чтобы он запускался один раз? (но, может быть, вы просто прокладываете себе почву вперед)

+0

Я использую ARC .. – Alessandro

+0

, кроме части '[annotationPoint release];' часть, код все равно должен работать нормально на ARC. Как я уже сказал, вы должны проверить, не вызван ли метод дважды. –

+0

Я называю это с помощью этой функции: UILongPressGestureRecognizer * longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget: self action: @selector (handleLongPressGesture :)]; [self.mapView addGestureRecognizer: longPressGesture]; – Alessandro