爲了我的項目的用戶界面,我在UIViewController的一個類別中創建了一個通用方法,它爲導航項目設置了UI。這種特殊的導航項目具有對應於一個動作(保存,OK,選擇等)和灰色按鈕黃色按鈕(取消,關閉)當已知該對象符合協議時,斷言對象包含某些方法是否是一種很好的模式?
- (void)configureAsSaveCancelIPadHeaderWithTarget:(id)theTarget actionForYellowButton:(SEL)selYellow actionForGrayButton:(SEL)selGray
我認爲我可以像這樣這種方法更小:
- (void)configureAsSaveCancelIPadHeaderWithTarget:(id<PSaveCancelViewControllerNavigationBar>)theTarget
並使目標響應協議。
該協議是這樣的:
@protocol PSaveCancelViewControllerNavigationBar <NSObject>
@required
- (void)save:(id)sender;
- (void)closeThisView:(id)sender;
@end
的@required
關鍵字只會給一個警告,如果不落實這些2種方法。
問題
是它認爲的良好格局中,如果目標包含這兩種方法的configureAsSaveCancelIPadHeaderWithTarget:
方法斷言?像這樣:
- (void)configureAsSaveCancelIPadHeaderWithTarget:(id<PSaveCancelViewControllerNavigationBar>)theTarget
{
NSAssert([theTarget respondsToSelector:@selector(save:)], @"The provided target must implement the PSaveCancelViewControllerNavigationBar protocol and have the methods defined in that protocol.");
NSAssert([theTarget respondsToSelector:@selector(closeThisView:)], @"The provided target must implement the PSaveCancelViewControllerNavigationBar protocol and have the methods defined in that protocol.");
我一定會再打這兩種方法(保存,closeThisView),所以我必須確保調用此方法的類已實現它們。
我不認爲這是一個「模式」的問題。這實際上取決於你希望如何防守以及缺少這些方法的可能性。通常,在調用委託方法時,在調用它之前檢查它是否存在。 – trojanfoe
@trojanfoe是的,謝謝。在這種情況下,我將選擇器分配給UIButton,因此在單擊按鈕之前沒有機會檢查選擇器是否存在。如果按下按鈕時該選擇器不存在,則應用程序將崩潰。 – Andrei
在這種情況下,我認爲使用斷言的方法是正確的,無論這些方法的「@ required」屬性如何。 – trojanfoe