2014-01-10 74 views
1

噹噹我創建一個協議 說: 使用創建協議

@protocol EBSoundViewProtocol <NSObject> 

- (void)playSoundPressed; 
- (void)soundHintPressed; 
- (void)crossOutLettersHintPressed; 
- (void)fillInLettersHintPressed; 
- (void)solveSoundHintPressed; 

@end 

,然後我在我的類創建委託屬性,它應該是這樣的:

@property (strong, nonatomic) id delegate; 

或等這樣的:

@property (strong, nonatomic) id<EBSoundViewProtocol> delegate; 

,因爲我真的不能圖中的分歧,我沒有測試,但我第一個想到的正常工作,所以我爲什麼需要?

+2

稍偏離主題,但委託屬性通常應該是弱引用。 –

回答

2

格雷迪球員是正確的;括號內的位只是表示對象應符合協議。如果您添加<EBSoundViewProtocol>,您將收到關於該協議的任何必需但未實現的方法的警告。

當宣佈協議,你還可以添加非所需的方法與@optional關鍵字,像這樣:

@protocol EBSoundViewProtocol <NSObject> 

- (void)playSoundPressed; 
- (void)soundHintPressed; 

@optional 

- (void)crossOutLettersHintPressed; 
- (void)fillInLettersHintPressed; 
- (void)solveSoundHintPressed; 

@end 

在這種情況下,你只需要實現協議的前兩種方法,以符合。其他三個可以安全地執行或忽略。

如果你省略了<EBSoundViewProtocol>,你應該換任何調用委託一起-respondsToSelector:代替通話,以確保該方法已實現:

if ([self.delegate respondsToSelector:@selector(playSoundPressed)]) { 
    [self.delegate playSoundPressed]; 
} 

無論哪種方式工作得很好。

哦,正如René指出的那樣,您應該使您的委託屬性變弱,而不是強大,以避免保留週期。

1

它應該是:

@property (strong, nonatomic) id<EBSoundViewProtocol> delegate; 

,因爲這告訴該委託執行協議EBSoundViewProtocol

+0

不會在沒有的情況下工作嗎? –

+0

無論哪種方式都有效,儘管您可能想要在調用委託之前使用-respondsToSelector:如果您關閉協議標識。 – atticus

2
@property (strong, nonatomic) id<EBSoundViewProtocol> delegate; 

編譯器,因爲這會給你一個警告:

obj.delegate = @"clearly doesn't adopt that protocol"; 
+0

,但它只是一個編譯器檢查,它不會影響運行時,只是一個很好的(鴨)式類型正確性機制。 –