1. 程式人生 > 程式設計 >swift中正確安全宣告一個單例的方法例項

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關鍵字的實際上是使用dispatch_once語法來實現的,如下一段swift編譯中間產物SIL語言中的程式碼就能看到底層的實現.

1.staic變數被宣告為全域性變數

// static TestShareInstance.shareInstane
sil_global hidden [let] @static main.TestShareInstance.shareInstane : main.TestShareInstance : $TestShareInstance

2.在get方法中獲取變數呼叫了swift內嵌的builtin "once",實際上呼叫的是swift_once方法

swift中正確安全宣告一個單例的方法例項

3.在swift原始碼中可以搜尋到swift_once方法的內部實現如下,內部呼叫的就是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,fn);
#else
 std::call_once(*predicate,[fn,context]() { fn(context); });
#endif
}

在類中,將TestShareInstance的init方法設定為了private,這能保證其他人沒有辦法呼叫你的init的方法,只能呼叫你的shareInstane單例變數;從而保證了單例的不可修改特性。如果你要強行修改,編譯器就會警告你,具體示例如下

swift中正確安全宣告一個單例的方法例項

到此這篇關於swift中正確安全宣告一個單例的文章就介紹到這了,更多相關swift正確安全宣告單例內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!