また1からこつこつと

最高はひとつじゃないと信じてまたがんばります。

AppDelegateをつかったクラス間値渡し

最近あまり技術的なことを書いていなかったので久しぶりに

今回はiOSアプリでAppDelegateを使った値渡しの話をしようと思います

クラス間の値渡し

たとえば、FirstViewControllerクラスからSecondViewControllerクラスに画面遷移したときに、入力した値も一緒に送信したい時がある。StoryBoardを使ってると結構簡単につくれるらしいのだけど、僕みたいに使わないひとだと結構めんどくさかった。そんなときに見つけたのがこのAppDelegateを使った値渡しの方法。

※もちろんDelegateを使った方法もありますが、今回はAppDelegateを使います

イメージ

イメージ的にはAppDelegateを媒介にする感じ。AppDelegateに変数を定義して、そこに値を格納していく。遷移先の画面からまたアクセスして値を取得しておく感じ。 まずはAppDelegateにおいておきたい変数を定義しておく。

[AppDelegate]

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    var userScore:Int?
    var userName:String?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        
        return true
    }

いま、AppDelegateのメンバ変数にuserScoreとuserNameをそれぞれ定義。続いてそれを取り出す処理をFirstViewControllerで書いてあげる。

[FirstViewControllerクラス]

import UIKit

class FirstViewController: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    
        appDelegate.userName = "mjk"
        appDelegate.userScore = 10

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

これでAppDelegateに値を置いておくことができたので、あとは遷移先のクラスで取得して処理してあげればよいだけ。

import UIKit

class SecondViewController: UIViewController, UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    
        println("Score:\(appDelegate.userScore)")
        println("Name:\(appDelegate.userName)")
       
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

SecondViewControllerがviewDidLoadされると、 Score:10 Name:mjk と表示されたら成功!

まとめ

今回は遷移する処理とかまったく書いてないので実際に使用するにはもう少し書かなきゃダメだけど、とりあえず要点はこんな感じ。ちょっとした値渡しを作るときに便利かと。