2011-11-22 39 views
0

爲什麼我的NSOperation子類在主線程上運行主方法?我希望它異步運行。NSOperation - 主要方法在主線程上運行?

@interface ServiceClient : NSOperation 
@end 

@implementation ServiceClient 

- (void)main 
{ 
    if ([[NSThread currentThread] isEqual:[NSThread mainThread]]) 
    { 
     NSLog(@"Why does this get called on the main thread"); 
    } 
} 

@end 

啓動操作

ServiceClient *serviceClient = [[ServiceClient aloc] init]; 
[serviceClient start]; 

編輯:

文檔建議重寫isCuncurrent和返回是的,但該方法不會被調用。

- (BOOL)isConcurrent 
{ 
    return YES; 
} 
+0

你是否從通過NSOperationQueue開始操作獲得相同的行爲? –

+1

出於興趣,[NSThread isMainThread]是否也返回true?我不確定你的平等測試。 – Senior

+0

我試圖將操作添加到NSOperationQueue並在後臺運行它(不同的線程),但是可以在單獨的線程上運行該操作而不將其添加到OperationQueue中? – aryaxt

回答

3

你需要建立自己的線程在start方法

段從Concurrency Programming Guide

開始
(必需)採取的所有併發操作必須重寫此方法並替換默認行爲與他們自己的自定義實現。要手動執行操作,請調用其啓動方法。因此,此方法的實現是您的操作的起點,並且是您設置執行任務的線程或其他執行環境的位置。你的實現不能在任何時候調用super。

如果您將NSOperation添加到NSOperationQueue它將爲您處理此問題。

相關問題