你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> IOS dispatch_once

IOS dispatch_once

編輯:IOS開發綜合
dispatch_once Executes a block object once and only once for the lifetime of an application.      void dispatch_once(    dispatch_once_t *predicate,    dispatch_block_t block); Parameters   predicate A pointer to a dispatch_once_t structure that is used to test whether the block has completed or not.   block The block object to execute once.   Discussion   This function is useful for initialization of global data (singletons) in an application. Always call this function before using or testing any variables that are initialized by the block.   If called simultaneously from multiple threads, this function waits synchronously until the block has completed.   The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.     dispatch_once不僅意味著代碼僅會被運行一次,而且還是線程安全的,這就意味著你不需要使用諸如@synchronized之類的來防止使用多個線程或者隊列時不同步的問題。     如果你要共享某個實例   +(MyInstance*)shareMyInstance()   {   static MyInstance *inst=nil;   static dispatch_once_t   p;   dispatch_once(&p,^{   inst=[[MyInstance alloc]init];   });   return inst;   }     你任何時候訪問共享實例,需要做的僅是:   MyInstance *myInst = [MyInstance  shareMyInstance];     就這樣,你在應用中就有一個共享的實例,該實例只會被創建一次。  
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved