0

There is a function which is need execute once in "view will appear".How should i do to solve the problem.
i have try

dispatch_once(&token) {     
}

But the 'dispatch once' is deprecated, so i am in trouble now.

Sunxb
  • 81
  • 1
  • 7
  • 1
    Clarify what you mean by "once". Once ever in the history of the app being installed? Once per execution of the app? Once per instance of the view controller? – rmaddy Nov 03 '16 at 03:28
  • per execution of the app, – Sunxb Nov 04 '16 at 06:51
  • OK, then this is a possible duplicate of http://stackoverflow.com/questions/37801407/whither-dispatch-once-in-swift-3 – rmaddy Nov 04 '16 at 13:53

1 Answers1

0

If you are doing this to spin up a single instance of some object for every instance of that view controller to share, then you may want to use lazy instantiation of a static property.

For example:

class Foo: UIViewController {
    static var monkey: Animal!

    func getMonkey() -> Animal {
        if Foo.monkey == nil {
            Foo.monkey = Monkey()  // we only make a new one if we don't have one
        }
        return Foo.monkey
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getMonkey().doSomething()  // you will always get the same monkey
    }
}