ios oc 和 swfit 用dispatch_once 建立單例

來源:互聯網
上載者:User

標籤:

網上已經有方法了,我這裡就是抄了下,原文連結

http://bj007.blog.51cto.com/1701577/649413

http://blog.csdn.net/u010124617/article/details/28856711?utm_source=tuicool

這裡的dispatch_once_t就是一個用於標記的整型,沒什麼特殊之處。

用dispatch_once實現單例的最大好處就是安全執行緒!!這個經常會被面試問到,建立資料庫和網路操作的單例時,確實存線上程安全問題。

先看oc的

+ (AccountManager *)sharedManager {     static AccountManager *sharedAccountManagerInstance = nil;     static dispatch_once_t predicate; dispatch_once(&predicate, ^{                 sharedAccountManagerInstance = [[self alloc] init];     });    return sharedAccountManagerInstance; }

再看swfit的,這裡使用了內部的struct是因為目前swift的class中不支援static定義類屬性。

class SwiftSingleton{    class func shareInstance()->SwiftSingleton{        struct YRSingleton{            static var predicate:dispatch_once_t = 0            static var instance:SwiftSingleton? = nil        }        dispatch_once(&YRSingleton.predicate,{                YRSingleton.instance=SwiftSingleton()            }        )        return YRSingleton.instance!    }}

 

ios oc 和 swfit 用dispatch_once 建立單例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.