Swift-沒(méi)有dispatch_once實(shí)現(xiàn)只調(diào)用一次

早在Swift 3的時(shí)候,dispatch_once就被蘋(píng)果廢棄了,并且推薦使用懶初始化全局變量方案代替。

dispatch_once報(bào)錯(cuò).png

官方推薦的解決辦法:

The free function dispatch_once is no longer available in Swift. In Swift, you can use lazily initialized globals or static properties and get the same thread-safety and called-once guarantees as dispatch_once provided. Example:

let myGlobal = { … global contains initialization in a call to a closure … }()

_ = myGlobal  // using myGlobal will invoke the initialization code only the first time it is used.

下面來(lái)介紹4種實(shí)現(xiàn)dispatch_once的只調(diào)用一次的方法

一. 帶立即執(zhí)行閉包初始化器的全局變量
let dispatchOnce: () = {
    print("dispatchOnce-------")
}()

/// 使用Aspects做交換: 用一個(gè)全局的常量來(lái)實(shí)現(xiàn)的dispatchOnce效果
let doSwizzles: () = {
    print("doSwizzles----")
    let oriSel1 = #selector(UIViewController.viewWillAppear(_:))
    let wrappedBlock: @convention(block) (AspectInfo, Bool) -> Void = { aspectInfo, _ in
        print("wrappedBlock---")
    }
    _ = try? UIViewController.aspect_hook(oriSel1, with: AspectOptions.positionBefore, usingBlock: wrappedBlock)

}()

// 之后在合適的時(shí)機(jī)使用變量,比如:
_ = dispatchOnce
二、全局常量
let foo = ViewController()

三、類(lèi),結(jié)構(gòu),枚舉中的靜態(tài)屬性

class Person22 {
    static var dog = Dog()
}
四、封裝一個(gè)once函數(shù)
public extension DispatchQueue {
    private static var _onceTracker = [String]()
    /// 函數(shù)只被執(zhí)行一次
    static func once(token: String, block: () -> ()) {

       // objc_sync_enter + objc_sync_exit 相當(dāng)于OC中的@sychronize() {}
        objc_sync_enter(self)
        defer {
            objc_sync_exit(self)
        }
        if _onceTracker.contains(token) {
            return;
        }
        _onceTracker.append(token)
        block()
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容