如何理解delegate (委托)设计模式
delegate (委托)設計模式
iOS 編程語言是 Objective-C,?? 簡稱 OC。 談起 OC的特性,人們常說,OC 不支持多繼承。但 Delegate 彌補了這個缺陷。 有了Delegate,?在聲明對象時,可以使其遵循多個協議。 從而解決了多繼承問題。 ?
Delegate ,又稱為 委托或代理, 它是一種設計模式。 ?學習iOS開發,需要深入理解?Delegate的用法。 Apple 對Delegate 有明確的說明。http://developer.apple.com/library/ios/#documentation/General/Conceptual/DevPedia-CocoaCore/Delegation.html????? 但理解起來還是有些抽象。
Delegate的用途:
用于改變或控制其他對象 。?
Delegate 的定義:
(1)Delegate 是一個對象, 其類型為 id? (anonymous type: 匿名類型);
(2) Delegate 的引用通常是一個實例變量?(instance variable), 命名為 delegate;
?(3)Delegate 內所用的方法是 訪問模式 (Accessors pattern)?
Delegate?Message 的命名:
發給Delegate的消息 通常帶有(should, will, did)?之一。 ????
should:期待delegate返回一個值;
will:表示變化發生之前 要做的事情;
did : 表示變化發生之后 要做的事情。
Cocoa Touh?的很多類都不同程度地用到Delgete。 比如: NSTextField, NSTableView。? 其中 NSTableView 還用到了 Data Source。
其實,Data Source 也是一種委托。?Data?Source?減少了 View 與 Model 之間的耦合性。 ???其中 , NSAppplication 實現了幾十個委托方法。
Delegate 使用的注意事項:
Delegate 是一個 ID 類型的對象, 同樣存在創建和釋放問題。 對于Data Source ,?只有Data?Source的使用者 (比如Table View)釋放后, Data Souce?才能被釋放。?否則,?就會出現crash。 因為在table view 獲取數據時, 數據已經不見了。 ??
Delegate 可用在多個場景下,比如對象間的數據交互,???不同視圖之間的行為交互。 若僅僅是數據交互, 可實現的方法還有很多。 Delegate 尤其適用于視圖之間的行為交互。
?這里通過 UIActionsheet 和 UIAlertView 的使用給以說明。
?UIActionsheet *actionsheet = [ [UIActionsheet alloc]
??????? initWithTile:@”Are you sure?”
???????delegate: self
??????? cancelButtonTitle: @”No Way!”
??????? destructiveButtonTitle: @”Yes, I’m sure!”
??????? otherButtonTitles: nil] ;
?
這里需特別注意 delegate:self 的使用方法。? 它表明 當 actionsheet 的button 被按下時, delegate 會收到通知。更確切地說, delegate 的actionsheet:didDismisswithButtonIndex: 方法將被調用。 將self作為 delegate 參數傳遞給該方法,可以確保 actionsheet:didDismisswithButtonIndex: 被調用。
?Cancelbutton 顧名思義,是取消按鈕。 ?與此相對應, destructiveButton 是確定按鈕。 通過delegate:self 設置,我們可以在 actionsheet:didDismisswithButtonIndex: 方法中判斷 用戶選擇的是 取消操作還是確定操作。
?如果沒必要區分 哪個按鈕給按下, 直接使用 UIAlertView 即可, 實例如下:
? UIAlertView *alert = [ [UIAlertView alloc]
??? ??????initWithTitle:@ “Something was done”
????????? message: @”Everything is OK”
????????? delegate: nil
????????? cancelButtonTitle:@”Cancel”
????????? OtherButtonTitles:nil ];
每個view 都有自己的delegate,同樣, UIAlertView 也有自己的delegate, 如果我們想知道用戶何時關閉了 AlertView 提示框,或想判斷用戶按下的是哪個按鈕,就可以使用 delegate:self。 其實這里的alertView 只是向用戶提供了一個按鈕,根本無需判斷用戶按下的是哪個按鈕,因此聲明 delegate:nil 即可。
轉載于:https://www.cnblogs.com/hopeanCom/archive/2012/11/02/2750913.html
總結
以上是生活随笔為你收集整理的如何理解delegate (委托)设计模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php中$GLOBALS
- 下一篇: asp.net MVC 路由