dispatch_once conversion Swift 3

2019-08-02 19:05发布

Below is my original code:

var checkUnauthorizedToken: dispatch_once_t = 0

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    dispatch_once(&checkUnauthorizedToken) { 
        if self.unauthorized {
            self.performSelector(#selector(self.displayUnauthorizedMessage), withObject: nil, afterDelay: 0.5)
        }
    }
}

as dispatch_once has been removed and I correct that I can just safely call the selector without it? e.g:

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        if self.unauthorized {
                self.performSelector(#selector(self.displayUnauthorizedMessage), withObject: nil, afterDelay: 0.5)
        }
    }

Is this correct?

标签: ios swift swift3
3条回答
对你真心纯属浪费
2楼-- · 2019-08-02 19:19

dispatch_once is no longer available in Swift so you should use lazily initialized or static properties. In this way you will get the same thread-safety and called-once guarantees as dispatch_once provided.

Example with static var:

//init static var
private static var callOne: () {  
     print("Call one") 
}() 

//call 
Class.callOne

Example with lazy var:

//init lazy var
lazy var callOne: () = {
     print("Call one")
}()

//call
 _ = self.callOne
查看更多
Juvenile、少年°
3楼-- · 2019-08-02 19:25

Normally, when you convert to swift3, it would automatically transform to something like this:

lazy var checkUnauthorizedToken: () = {
    if self.unauthorized {
       self.performSelector(#selector(self.displayUnauthorizedMessage), withObject: nil, afterDelay: 0.5)
    }
}()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    _ = self.checkUnauthorizedToken
}
查看更多
祖国的老花朵
4楼-- · 2019-08-02 19:34

Well it is not the same thing. I'm not sure what your exact intention is, but I think what you do is overkill.

dispatch_once was to make sure that a code is only executed once, even if multiple threads are calling a function and it is usually used to initialize variables in a function that is called often and maybe from different threads.

Since viewDidAppear will be always called in the main thread and you just want to show a unauthorized view on first visit of the view I would suggest you do a simple instance bool variable unauthorizedMessageShown, set it to true on first visit and check that in the function.

查看更多
登录 后发表回答