views:

126

answers:

2

Hi,

I am new for iPhone programming.

I just want to implement a samll function that allows system to obtain a location on MKMapView where the user has touched. I wrote some code as following:

#import "UIViewTouch.h"


@implementation UIViewTouch
@synthesize viewTouched;

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *) event{
    NSLog(@"Hit Test");
    NSLog(@"x = %f, y = %f", point.x, point.y);
    MKMapView *mapView = (MKMapView *) [self.subviews objectAtIndex:0];
    CLLocationCoordinate2D coordinate = [mapView convertPoint:point toCoordinateFromView:self];
    NSLog(@"Lat = %f, Lng = %f", coordinate.latitude,coordinate.longitude);
        //MapAnnotation is a custom class and confirms to MKAnnotation.
    MapAnnotation *annotation = [[MapAnnotation alloc] initWithCoordinate:coordinate];
    [mapView addAnnotation:annotation];
    return [super hitTest:point withEvent:event];
}

- (BOOL) pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    return [super pointInside:point withEvent:event];
}

@end

It can work fine if I don't add a annotation on the MKMapView, otherwise the app will throw a exception: "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TESTViewController openCallout:]: unrecognized selector sent to instance 0x6b60180'"

Any idea? Thanks a lot!

A: 

Your code looks fine to me. What does the call stack look like at the exception point? Do you have any calls to the apparently nonexistent selector -openCallout:?

Seamus Campbell
A: 

Not entirely related, but you should implement touch-handling in touchesBegan:withEvent:. Spontaneously adding an annotation in hitTest:withEvent: is dubious at best, since it'll probably add a view to the map view...

tc.