我有幾個方法調用是這樣的:如何讓一段代碼在單獨的線程中運行?
[self myFoo];
[self heavyStuff]; // this one in other thread
[self myBar];
我要看看哪個類/方法?當我搜索「線程」時,會出現很多類,方法和函數。哪一個在這裏最合適?
我有幾個方法調用是這樣的:如何讓一段代碼在單獨的線程中運行?
[self myFoo];
[self heavyStuff]; // this one in other thread
[self myBar];
我要看看哪個類/方法?當我搜索「線程」時,會出現很多類,方法和函數。哪一個在這裏最合適?
你會做
[self performSelectorInBackground:@selector(heavyStuff) withObject:nil];
見NSObject的reference在蘋果的網站。
你可以使用NSOperationQueue和NSInvocationOperation:
[self myFoo];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(heavyStuff) object:nil];
[operationQueue addOperation:operation];
[self myBar];
對於 「射後不理」,嘗試[self performSelectorInBackground:@selector(heavyStuff) withObject:nil]
。如果您有多個此類操作,則可能需要檢出NSOperation
及其子類NSInvocationOperation
。 NSOperationQueue
管理線程池,併發執行的操作,包括通知或封鎖方式號碼時,所有操作完全告訴你:
[self myFoo];
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(heavyStuff) object:nil];
[operationQueue addOperation:operation];
[operation release];
[self myBar];
...
[operationQueue waitUntilAllOperationsAreFinished]; //if you need to block until operations are finished
在一個較低的水平,你可以使用使用-[NSThread detachNewThreadSelector:@selector(heavyStuff) toTarget:self withObject:nil]
。
你在這裏有很多偉大的指針,但不要忘記花費一些時間與Threading Programming Guide。它不僅提供了有關技術的良好指導,而且還提供了良好的併發處理設計,以及如何更好地利用運行循環與線程而不是線程。
如果你專門針對Snow Leopard中,你可以使用大中央調度:
[self myFoo];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self heavyStuff];
dispatch_async(dispatch_get_main_queue(), ^{
[self myBar];
});
});
但它不會在早期系統(或iPhone)上運行,並可能是矯枉過正。
編輯:它適用於iPhone自iOS 4.x以來的版本。
在performSelectorInBackround中缺少'g' – Erich 2009-12-23 17:31:02
已修復。謝謝@Erich。 – 2009-12-23 18:21:00