2014-02-14 42 views

回答

7

您可以使用Grand Central Dispatch此:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions), ^{ 
    // Call your method. 
}); 
+0

這是遞歸調用它嗎? – Tukajo

+0

我現在看到你已經標記了「遞歸」問題。不,這只是執行你在後臺線程中的代碼塊。您當然可以使用GCD與遞歸或迭代相結合。 GCD的目的是改進併發代碼執行。 – geraldWilliam

+2

對於那些發現這個問題的人,一定要查看0x7fffffff關於dispatch_apply的答案。 – geraldWilliam

1

你可以使用:

[self performSelectorInBackground:@selector(aMethod) withObject:nil]; 

對於不帶參數的方法。或者像

[self performSelectorInBackground:@selector(otherMethodWithString:andData:) withObjects:string, data, nil]; 

如果你有參數。

1

下面是另一個例子,解釋如何執行背景隊列並在其中進行迭代。

- (void)method 
{ 
    // start a background proccess that will not block the UI 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 

     for (int i = 0; i < 1000000; i++) { 

      if (i == 999) { 

       // Need to iterate with interface elements when inside a background thread. 
       dispatch_async(dispatch_get_main_queue(), ^{ 
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Found" message:@"Found your number" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 
        [alertView show]; 
       }); 
      } 

      NSLog(@"Count: %d",i); 
     } 

    }); 
} 
+0

你想'我<1000000',而不是'I> 1000000'。 – rmaddy

+0

謝謝,修復它。 – alexandresoli

+0

它只顯示一個提醒,當它發現號碼999. – alexandresoli

1

正如其他人所指出的那樣,使用GCD絕對是一種好方法。

或者,如果您希望操作可以被取消(例如加載Web資源),您可以考慮子類化NSOperation並檢查isCancelled

AFNetworking實際上做到這一點(在製造/管理Web請求例如AFHTTPRequestOperationManager)。)

結帳上NSOperation蘋果文檔,也this tutorial on Ray Wenderlich's siteNSOperation S比細節。

5

你一定想用Grand Central Dispatch來做到這一點,但我只想指出,GCD有一個方法來構建這種類型的東西。 dispatch_apply()在您選擇的隊列中執行指定次數的區塊,當然,還要跟蹤您沿途正在進行的迭代。下面是一個例子:

size_t iterations = 10; 

dispatch_queue_t queue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL); 

dispatch_apply(iterations, queue, ^(size_t i) { 
    NSLog(@"%zu",i);// Off the main thread. 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     // Go back to main queue for UI updates and such 
    }); 
});