2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】初心者による優しいデリゲート

Posted at

はじめに

間違いがあるかもしれないです。
間違っていたらコメントください

delegateを使ってViewに通知する方法を学んだので記録しておきます。

実装

ViewController
import UIKit

class ViewController: UIViewController, SampleModelDelegate {

    private let sampleModel = SampleModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        sampleModel.delegate = self
        
        // ここでリクエスト
        sampleModel.fetchAPI()
    }

    func sampleModel(_ sampleModel: SampleModel) {
        print("レスポンスが返ってきました")
    }
}
SampleModel
import Foundation

protocol SampleModelDelegate: AnyObject {
    func sampleModel(_ sampleModel: SampleModel)
}

class SampleModel {
    weak var delegate: SampleModel?

    func fetchAPI() {
        // APIリクエスト...
        // レスポンスが返ってきたら通知
        // ↓ API待ってる代わり
        Thread.sleep(forTimeInterval: 5)

        // ここでView側にあるsampleModelが実行される
        delegate?.sampleModel(self)
    }
}

おわり

どのようにデリゲートが実行されているのか知らなかったので勉強になりました。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?