- iOS Programming Cookbook
- Hossam Ghareeb
- 259字
- 2021-07-09 18:29:42
Delegation
Delegation is the most commonly used design pattern in iOS. In delegation, you enable types to delegate some of its responsibilities or functions to another instance of another type. To create this design pattern, we use protocols that will contain the list of responsibilities or functions to be delegated. We usually use delegation when you want to respond to actions or retrieve or get information from other sources without needing to know the type of that sources, except that they conform to that protocol. Let's take a look at an example of how to create use delegate:
@objc protocol DownloadManagerDelegate { func didDownloadFile(fileURL: String, fileData: NSData) func didFailToDownloadFile(fileURL: String, error: NSError) } class DownloadManager{ weak var delegate: DownloadManagerDelegate! func downloadFileAtURL(url: String){ // send request to download file // check response and success or failure if let delegate = self.delegate { delegate.didDownloadFile(url, fileData: NSData()) } } } class ViewController: UIViewController, DownloadManagerDelegate{ func startDownload(){ letdownloadManager = DownloadManager() downloadManager.delegate = self } func didDownloadFile(fileURL: String, fileData: NSData) { // present file here } func didFailToDownloadFile(fileURL: String, error: NSError) { // Show error message } }
The protocol DownloadManagerDelegate contains methods that would be called once the specific actions happen to inform the class that conforms to that protocol. The DownloadManager class performs the download tasks asynchronously and informs the delegate with success or failure after it's completed. DownloadManager doesn't need to know which object will use it or any information about it. The only thing it cares about is that the class should conform to the delegate protocol, and that's it.
- Linux運維之道(第3版)
- 鴻蒙生態:開啟萬物互聯的智慧新時代
- SharePoint 2013 應用開發實戰
- Windows Server 2012網絡操作系統企業應用案例詳解
- Windows 7應用入門與技巧
- Kali Linux高級滲透測試
- 跟老男孩學Linux運維:Shell編程實戰
- Kali Linux高級滲透測試(原書第3版)
- UI設計手繪表現從入門到精通
- Linux內核API完全參考手冊(第2版)
- OpenVZ Essentials
- Less Web Development Essentials
- BuddyPress Theme Development
- STM32庫開發實戰指南
- 分布式實時處理系統:原理、架構與實現