dispatch_once 转换 Swift 3 [英] dispatch_once conversion Swift 3

查看:29
本文介绍了dispatch_once 转换 Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的原始代码:

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)
        }
    }
}

因为 dispatch_once 已被删除,我更正我可以在没有它的情况下安全地调用选择器?例如:

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)
        }
    }

这是正确的吗?

推荐答案

这不是一回事.我不确定您的确切意图是什么,但我认为您的做法太过分了.

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 是为了确保代码只执行一次,即使多个线程正在调用一个函数,它通常用于初始化经常调用的函数中的变量,并且可能来自不同的线程.

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.

由于 viewDidAppear 将始终在主线程中调用,而您只想在第一次访问视图时显示未经授权的视图,我建议您做一个简单的实例 bool 变量 unauthorizedMessageShown,在第一次访问时将其设置为 true 并在函数中检查.

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.

这篇关于dispatch_once 转换 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆