Example of dispatch_once in Swift

前端 未结 3 551
终归单人心
终归单人心 2020-12-30 06:36

Is there an example of how dispatch_once should be used in Swift? (Preferably one from Apple.)

Note: In this case, I\'m not using it for a singleton

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 06:46

    For those of you who are curious, for me this approach has been useful for this purpose:

    class SomeVC : UIViewController {
        private var token: dispatch_once_t = 0
    
        public override func viewDidAppear(animated: Bool) {
            super.viewDidAppear(animated)
    
            dispatch_once(&token) { () -> Void in
                self.doSomethingOnce()
            }
    
        }
    }
    

    By not declaring a static var it has the expected behaviour. That being said, this is definitely NOT RECOMMENDED for any serious project, since in the Docs (as your well said) it states:

    The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage (including Objective-C instance variables) is undefined.

    If we don't want to run into any future weird bugs and undefined behaviour I would just stick to what Apple says. But it's still nice to play around with these things, isn't it? =)

提交回复
热议问题