2011-10-05 184 views
2

我想用一個可選的委託方法擴展UIAlertViewDelegate協議。UIAlertViewDelegate擴展協議

接口

@protocol HPAlertViewDelegate; 

@interface HPAlertView : UIAlertView<UIWebViewDelegate>{ 
    id <HPAlertViewDelegate> delegate; 
    UIWebView *webView; 
} 

@property (nonatomic, assign) id <HPAlertViewDelegate> delegate; 
@property (nonatomic, retain) UIWebView *webView; 


- (id)initWithWebURL:(NSString *)url title:(NSString *)aTitle; 

@end 

@protocol HPAlertViewDelegate <UIAlertViewDelegate> 

@optional 
- (void)HPAlertViewWebViewDidLoad:(HPAlertView *)alertView; 

@end 

實施

@dynamic delegate 

當我使用它在myViewController像:

HPAlertView *alertView = [[HPAlertView alloc] initWithWebURL:myURL tile:myTitle]; 
[alertView setDelegate:self]; 

我有2個問題:

  • 如果我委託設爲@dynamic,我在HPAlertView委託總是空,即使setDelegate:自

  • 如果我委託設爲@synthesize,我代表響應僅適用於新的@optional委託方法,而不適用於UIAlertView委託方法。

+0

我知道這不是你要求的,但你不應該真的繼承'UIAlertView'。 – hypercrypt

回答

1

嘗試@synthesize,然後實現setter方法,因爲這:

- (void)setDelegate:(id)aDelegate { 
    super.delegate = aDelegate; 
    delegate = aDelegate; 
} 

我猜@synthesize你們班會生成一個名爲delegate是從超類delegate實例變量不同的一個新的實例變量。你可以在這裏閱讀更多關於這個:http://cocoawithlove.com/2010/03/dynamic-ivars-solving-fragile-base.html

+0

謝謝,但沒有,如果我這樣做,我會在setDelegate上產生無限循環(self.delegate = [self setDelegate],所以....) –

+0

是的,我剛剛注意到並更改了代碼 –

+0

它工作嗎?只是好奇:) –