Search code examples
iphoneobjective-cmkmapviewmkannotation

MKAnnotation constructor error


I'm having a problem with MKAnnotation, i created a class "cgdMapAnnotation" for annotations and one of it's constructor is like this:

+ (id) initWithCoordinate:(CLLocationCoordinate2D)coordinate andTitle:(NSString*) title andSubtitle:(NSString*) subtitle {
    self = [super alloc];
    _coordinate = coordinate;
    _title = [title retain];
    _subtitle = [subtitle retain];
    return self;
}

The problem is that when i call:

cgdMapAnnotation *placemark=[[[cgdMapAnnotation alloc]    initWithCoordinate:centerCoordinate andTitle:@"Title" andSubtitle:@"SubTitle" ] autorelease];

I get in the console the following error:

-[cgdMapAnnotation initWithCoordinate:andTitle:andSubtitle:]: unrecognized selector sent to instance 0x33cf2fe0

I really don't understand what's the problem. Can someone help?

Thanks in advance.


Solution

  • First, convention has it that class names start with a capital letter. So cgdMapAnnotation should be CgdMapAnnotation or CGDMapAnnotation.

    Second, there are a few problems with initWithCoordinate:andTitle:andSubtitle:.

    • It is declared as a class method using the '+' at the beginning of the name, but you are attempting to use it as an instance method. [cgdMapAnnotation alloc] will return an instance of cgdMapAnnotation. So you are
    • self = [super alloc] does not make sense in this class method.

    Your method should probably look like this:

    - (id)initWithCoordinate:(CLLocationCoodinate2D)coordinate andTitle:(NSString*) title andSubtitle:(NSString*) subtitle
    {
      if( self = [super init] )
      {
        _coordinate = coordinate;
        _title = [title retain];
        _subtitle = [subtitle retain];
      }
    
      return self;
    }