官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 彭阳县| 大英县| 乌鲁木齐县| 东辽县| 利辛县| 临湘市| 县级市| 景宁| 彰化市| 贵阳市| 西盟| 油尖旺区| 阿鲁科尔沁旗| 莲花县| 湘乡市| 阿鲁科尔沁旗| 奉化市| 杂多县| 楚雄市| 开封市| 法库县| 广汉市| 兴业县| 通化市| 永顺县| 恭城| 漳平市| 会理县| 本溪市| 上高县| 沾化县| 麻阳| 丰原市| 海林市| 仪陇县| 岐山县| 本溪市| 孝感市| 刚察县| 方正县| 弋阳县|