2011-08-29 22 views
0

我想分類的UIBUTTON類,並添加一些額外的手段。iPhone,試圖繼承UIButton和meeds所有崩潰,當你打電話給他們

如果我ceate一類如下

cTest *mTest=[cTest buttonWithType:UIButtonTypeRoundedRect]; 

和調用任何基法,一個我創建或媒體鏈接存在,例如[cTest setTitle:@"test" forState: UIControlStateNormal];崩潰。

我CTEST類:

#import <Foundation/Foundation.h> 

@interface cTest : UIButton { 
    int i; 
} 

-(void) aTest; 

@end 

代碼來測試類:

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

// this works fine 
    UIButton *mBut=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    [mBut setTitle:@"test" forState: UIControlStateNormal]; 


// this does NOT 
    cTest *mTest=[cTest buttonWithType:UIButtonTypeRoundedRect]; 
    [cTest setTitle:@"test" forState: UIControlStateNormal]; 
    [mTest aTest]; // crashes here does not call my function 
} 

特德

回答

0

UIButton buttonWithType:只是返回一個UIButton *對象,而不是cTest *對象。

你西港島線必須提供一個類的方法(工廠方法) +(CTEST *)cTestWithType:

一個不打電話[超級buttonWithType:...]沒有。 而不是你將不得不創建一個新的cTest對象與分配(並保留或autorelease,什麼永遠服務你的目的最好),並通過設置buttonType屬性來初始化它。

...或者只是在不提供工廠方法的情況下執行相同操作。

0

+buttonWithType:不保證返回這就是所謂的類的實例。如果您指定UIButtonTypeRoundedRect,則將返回UIButton的私有子類:UIRoundedRectButton

要獲取您的子類的實例,請覆蓋+buttonWithType:或調用不同的初始化程序,如-initWithFrame:-init

相關問題