Trong iOS, delegate pattern hoạt động ra sao? Khi nào nên dùng delegate thay vì closure?
Trong iOS, delegate pattern hoạt động ra sao? Khi nào nên dùng delegate thay vì closure?
Delegate pattern: một object (delegator) uỷ quyền một số hành vi/ thông báo cho object khác (delegate) thông qua một protocol.
protocol DownloaderDelegate: AnyObject {
func downloader(_ d: Downloader, didFinishWith data: Data)
func downloader(_ d: Downloader, didFailWith error: Error)
}
final class Downloader {
weak var delegate: DownloaderDelegate? // weak để tránh retain cycle
func start() { /* ... */ delegate?.downloader(self, didFinishWith: data) }
}
final class ViewController: UIViewController, DownloaderDelegate {
func downloader(_ d: Downloader, didFinishWith data: Data) { /* cập nhật UI */ }
}
downloader.delegate = self
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.