LoginSignup
16
14

More than 5 years have passed since last update.

[Swift]viewWillAppearなどで一度だけ実行したい処理を書く (Swift3対応)

Last updated at Posted at 2016-10-20

SwiftでiOS開発をしているとviewWillAppearなどで一度だけ実行したい処理を書きたい場面がある。
Swift3になりdispatch_onceでかけなくなったりと困っている人がいると思います。

シンプルに簡単に実現するための処理を書きました。

まず以下のClassを生成する

OnceExec.swift
class OnceExec {
    var isExec = false
    func call(onceExec: ()->()){
        if !isExec {
            onceExec()
            isExec = true
        }
    }
}

そして使用したいViewControllerで
以下を書く。

//実行したいClass内部に記載
var onceExec = OnceExec()

//viewWillAppearとかに書く
override func viewWillAppear(_ animated: Bool) {
    onceExec.call {
        //一度だけ実行したい処理メソッド
    }
}
16
14
4

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
16
14