2011-04-19 133 views
0
我在與MKAnnotation問題

,我創建了一個類「cgdMapAnnotation」的註解,它的構造函數的一個是這樣的:MKAnnotation構造錯誤

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

的問題是,當我打電話:

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

我在控制檯收到以下錯誤:

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

我真的不瞭解什麼是問題。有人可以幫忙嗎?

在此先感謝。

回答

1

首先,慣例是它的類名以大寫字母開頭。所以cgdMapAnnotation應該是CgdMapAnnotation或CGDMapAnnotation。

其次,initWithCoordinate存在一些問題:andTitle:andSubtitle :.

  • 它在名稱的開頭使用'+'聲明爲類方法,但您試圖將其用作實例方法。 [cgdMapAnnotation alloc]將返回一個cgdMapAnnotation的實例。所以你是
  • self = [super alloc]在這個類方法中沒有意義。

你的方法或許應該是這樣的:

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

    return self; 
} 
+0

謝謝!就是這樣。這是我的第一個iPhone項目,所以只是一個新手。順便說一下,類方法中的「 - 」和「+」有什麼區別? 「 – Rui 2011-04-19 18:56:41

+1

」+「表示類方法,因此可以在類對象上調用它。 UIButton的buttonWithType就是一個例子。所以你可以調用[UIButton buttonWithType:TYPE]。 「 - 」表示一個實例方法,因此它在一個類的實例上被調用。一個例子就是UIButton的imageForState。所以你可以調用[someButton imageForState:STATE]。 – cgarman 2011-04-19 20:28:31

+0

謝謝!真的很感謝幫助。 – Rui 2011-04-19 22:21:35