swift中正確安全聲明一個單例的方法實例
Talk is cheap. Show me the code.
class TestShareInstance{
var age:Int
static let shareInstane:TestShareInstance = TestShareInstance(age: 3);
private init(age:Int){
self.age = age;
};
}
說說原理
swift在類中,類變量是能夠保證線程安全,swift底層,static關(guān)鍵字的實際上是使用dispatch_once語法來實現(xiàn)的,如下一段swift編譯中間產(chǎn)物SIL語言中的代碼就能看到底層的實現(xiàn).
1.staic變量被聲明為全局變量
// static TestShareInstance.shareInstane sil_global hidden [let] @static main.TestShareInstance.shareInstane : main.TestShareInstance : $TestShareInstance
2.在get方法中獲取變量調(diào)用了swift內(nèi)嵌的builtin "once",實際上調(diào)用的是swift_once方法

3.在swift源碼中可以搜索到swift_once方法的內(nèi)部實現(xiàn)如下,內(nèi)部調(diào)用的就是GCD底層的dispatch_once_f,保證了單例的線程安全。
/// Runs the given function with the given context argument exactly once.
/// The predicate argument must point to a global or static variable of static
/// extent of type swift_once_t.
void swift::swift_once(swift_once_t *predicate, void (*fn)(void *),
void *context) {
#if defined(__APPLE__)
dispatch_once_f(predicate, context, fn);
#elif defined(__CYGWIN__)
_swift_once_f(predicate, context, fn);
#else
std::call_once(*predicate, [fn, context]() { fn(context); });
#endif
}
在類中,將TestShareInstance的init方法設(shè)置為了private,這能保證其他人沒有辦法調(diào)用你的init的方法,只能調(diào)用你的shareInstane單例變量;從而保證了單例的不可修改特性。如果你要強行修改,編譯器就會警告你,具體示例如下

到此這篇關(guān)于swift中正確安全聲明一個單例的文章就介紹到這了,更多相關(guān)swift正確安全聲明單例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用swift實現(xiàn)卡片橫向滑動動畫效果的方法示例
卡片橫向滑動動畫效果相信對大家來說都不陌生,下面這篇文章主要給大家介紹了關(guān)于利用swift實現(xiàn)卡片橫向滑動動畫效果的方法示例,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-07-07
Swift HTTP加載請求Loading Requests教程
這篇文章主要為大家介紹了Swift HTTP加載請求Loading Requests教程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
詳解Swift語言的while循環(huán)結(jié)構(gòu)
這篇文章主要介紹了Swift語言的while循環(huán)結(jié)構(gòu),包括do...while循環(huán)的用法,需要的朋友可以參考下2015-11-11
Swift實現(xiàn)監(jiān)聽鍵盤通知及一些處理詳解
這篇文章主要給大家介紹了關(guān)于Swift實現(xiàn)監(jiān)聽鍵盤通知及一些處理的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2018-01-01

