【Swfit】Swift與OC兩種文法寫單例的區別

來源:互聯網
上載者:User

標籤:

Swift與OC兩種文法寫單例的區別

例如寫一個NetworkTools的單例

(1)OC寫單例

 1 + (instancetype)sharedNetworkTools { 2     static id instance; 3      4     static dispatch_once_t onceToken; 5      6     dispatch_once(&onceToken, ^{ 7         instance = [[self alloc] init]; 8         //這裡可以做一些初始化 9     });10     11     return instance;12 }

 

 

(2)Swift寫單例

1     // 定義一個私人的靜態成員2     // `let` 就是安全執行緒的3     // 這句代碼懶載入的,在第一次調用的時候,才會運行4     private static let instance = NetworkTools()5     6     class func sharedNetworkTools() -> NetworkTools {7         return instance8     }

假如要預先初始化一些屬性,則可以這麼寫

 1  private static let instance : NetworkTools = { 2            let netWorkTool = NetworkTools() 3           //這裡初始化屬性 4          5            return netWorkTool 6     }() 7      8     class func sharedNetworkTools() -> NetworkTools { 9         return instance10     }

 

【Swfit】Swift與OC兩種文法寫單例的區別

相關文章

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.