カレントなクラスから別クラスに定義している要素を呼び出す場合にDelegateを使うと便利
- 参照したい処理が別クラスに定義されており、同インスタンス上にオブジェクトが存在せず参照できない場合にハマッた時のメモ
やりたいこと
Delegateを使ってクラスBにクラスAの処理を委譲する
サンプル処理フロー
- HogeViewController.swiftには画面を構成する要素を定義
- FugaRequestViewController.swiftにはモデルの処理を行うアクションを定義
- モデルの処理に失敗する
- アラートを出す
実現する為に使用する手段
- HogeViewController.swift上にDelegateを用意し、FugaRequestViewControllerクラスからHogeViewControllerクラスに処理を委譲する
HogeViewController.swift
class HogeViewController:UIViewController, HogeViewControllerDelegate {
let fugaRequest:FugaRequestViewController = FugaRequestViewController()
// MARK: Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
// ここでデリゲートにHogeViewControllerのインスタンスを渡す
self.fugaRequest.HogeViewControllerDelegate = self
}
// MARK: Gesture
@IBAction func onTappedAction(sender: AnyObject)
{
// タップするとhttpリクエストを実行する
fugaRequest.fetchRequest()
}
// アラート処理関数を定義。今回はデリゲートを使って動かす
func showAlertWithTitleAndMessage(titleStr:String,
messageStr:String)
{
let alert:UIAlertController = UIAlertController(title:titleStr,
message:
messageStr,
preferredStyle: UIAlertControllerStyle.Alert)
let defaultAction = UIAlertAction(title: "OK",
style: .Default,
handler: nil)
alert.addAction(defaultAction)
presentViewController(alert,
animated: true,
completion: nil)
}
}
FugaRequestViewController.swift
protocol HogeViewControllerDelegate
{
// デリゲート関数を定義
func showAlertWithTitleAndMessage(titleStr:String, messageStr:String)
}
class FugaRequestViewController:UIViewController
{
// MARK: Life Cycle
override func viewDidLoad()
{
super.viewDidLoad()
}
// httpリクエストを実行する関数
func fetchRequest()
{
let urlString : NSURL = NSURL({/* {APIリクエスト先のURLを記述} */})!
let request : NSURLRequest = NSURLRequest(URL:urlString)
// 非同期処理呼び出し
NSURLConnection.sendAsynchronousRequest(request,
queue: NSOperationQueue.mainQueue(),
completionHandler: self.requestCallback()
}
// 処理取得結果処理
func requestCallback(res:NSURLResponse?,
data:NSData?,
error:NSError?)
{
if (error?.domain == NetWorkErrorCause) {
// エラーの場合に、HogeViewController上でアラートを出す
HogeViewControllerDelegate?.showAlertWithTitleAndMessage("エラータイトル",
messageStr: "エラーが発生しました")
return
}
// レスポンスの処理
}
}