LoginSignup
6
6

More than 5 years have passed since last update.

unwindSegueで元の画面へ戻る時のメソッド実行順

Posted at

すごいハマって時間を浪費したのでメモ。

【現象】
unwindSegueでTableViewControllerから元の画面へ戻って値を渡そうとした際に、tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)で共通変数に値を入れて値渡しをしようとしても、あれ?値が渡せない。。って状態になった。

【原因】
メソッドの実行順として、didSelectRowAtIndexPathはprepareForSegueやunwindSegueで呼び出される処理よりも後に実行されるため

【検証】
以下のように画面Aから画面Bへ戻る場合を想定。

blogimage1.png

準備したメソッドは以下のとおり。

(A)ViewController.swift
@IBAction func exitFromTableView(segue: UIStoryboardSegue){
        println("exitFromTableView (unwindSegue)")
    }

*戻ってくる際のunwindSegue用のメソッド

(B)TableViewController.swift
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
        println("prepareForSegue")
    }

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        println("didSelectRowAtIndexPath")
    }

これでTableViewCellをクリックするとログはこのように出力される。

スクリーンショット 2015-05-02 14.06.04.png

まとめると、以下の順番でメソッドは実行されるので
実装する際は注意しよう。

  1. prepareForSegue
  2. unwindSegueで呼ばれるメソッド
  3. Cellがクリックされた時のdidSelectRowAtIndexPathのメソッド

おわり。

6
6
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
6
6