2016-02-18 21 views
0

執行靜態函數(的一部分),我有一個函數(無論是靜態函數或完全無關聯的一個)和特定線程在一個特定的線程

class AnyClass{ 
    static func foo(myThread: NSThread) { 
     .... 
     // I want this *blablabla* to be performed on myThread 
     .... 
    } 
} 

我怎樣才能是怎樣呢?

回答

0

請勿使用線程,而應使用調度隊列(Grand Central Dispatch)。請參閱Apple的Migrating away from threads文檔。

爲GCD一個典型的使用模式是:

class AnyClass{ 
    static func foo(queue: dispatch_queue_t) { 
     .... 

     let group = dispatch_group_create(); 
     dispatch_group_enter(group) // tell the OS your group has started 
     dispatch_group_async(group, queue) { 
      // Do your things on a different queue 
      .... 
      dispatch_group_leave(group) // tell the OS your group has ended 
     } 

     // Do your other things on the original thread simultaneously 
     .... 

     dispatch_group_wait(group, DISPATCH_TIME_FOREVER) // wait for the queue to finish 

     // Do other things still 
     .... 
    } 
} 

// Calling the function 
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
AnyClass.foo(queue)