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?
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 asdispatch_once
provided.Example with static var:
Example with lazy var:
Normally, when you convert to swift3, it would automatically transform to something like this:
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 variableunauthorizedMessageShown
, set it to true on first visit and check that in the function.