LoginSignup
1
1

More than 5 years have passed since last update.

AppDelegateに処理を任せる

Posted at

クラス一つ一つに同じ処理を書くのは冗長なので、デリゲートを利用する。

AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
...
  func getValue(key: String) -> String {
    if key == "key1" {
      return "value1"
    } else if key == "key2" {
      return "value2"
    }
    return ""
  }
}
FirstViewController.swift
import UIKit

class FirstViewController: UIViewController {
  let myDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
...
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    let value = myDelegate.getValue("key1")
  }
}
SecondViewController.swift
import UIKit

class SecondViewController: UIViewController {
  let myDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
...
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    let value = myDelegate.getValue("key2")
  }
}
1
1
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
1
1