2012-12-08 45 views
0

我新手,這個所以請原諒我的任何錯誤......多線程與NSThread

我的情況:

- (id)initWith... //Some arguments 

有它返回一個對象的初始化方法。它使用參數的值設置它的實例變量做了很多工作。爲了最大限度地提高性能,我將工作分爲兩個線程一個線程設置一組相關變量,另一個線程設置另一組相關變量。

- (id)initWith:arguments { 
self = [super init]; 
if (self) { 
[NSThread detachNewThreadSelector:@selector(setFirstSetOfVariables:) toTarget:self withObject:argObject]; 
[self setSecondSetOfVariables:arguments]; 
//Check if the thread finished its work and return the value 
return self; 
} 

爲了方便起見,認爲該方法必須設置的兩組變量沒有任何關係。那麼我的問題是:如何檢查第一個線程是否完成?我可以創建一個BOOL var,但我必須創建一個循環來檢查。我也可以調用一種方法來說明它已準備就緒。但是,由於我不知道很多,所以我不知道在線程中調用的方法會在主線程中運行還是在其他線程中運行。抱歉。感謝您的任何信息。

+1

是否有原因,你在init方法中做了很多工作。我認爲最好創建對象,然後調用對象上的另一個方法來創建所有其他值。我建議你閱讀GCD或其他簡單的執行背景工作的方法。即使Apple建議不要使用NSThread類,並且事實上甚至在其「併發編程指南」中也放棄了對NSThread的討論。 – Srikanth

+2

@Srikanth說什麼;通常不鼓勵使用NSThread。在'init'中進行重量初始化也是不鼓勵的。您真的想要構建您的應用程序,以便您可以將「設置所有對象」從「OK,GO!」中分離出來。 – bbum

回答

0

你能做到這樣簡化了整個事情

ComplicatedObject *myComplicatedObject = [ComplicatedObject alloc] init; 

[myComplicatedObject setLongTimeTakingVariables]; 

,並在ComplicatedObject創建方法類似

-(void)setLongTimeTakingVariables{ 
    dispatch_async(dispatch_get_global_queue(),^{ All of your code can go here. Infact you need not split it into two sections, because it will happen in the background and your userinterface will not get affected } 

但是,如果要分割那麼你可以做

dispatch_async(dispatch_get_global_queue((DISPATCH_QUEUE_PRIORITY_LOW, 0)),^{ 
        some work here 
    } 

    dispatch_async(dispatch_get_global_queue((DISPATCH_QUEUE_PRIORITY_LOW, 0)),'{ 
        some other work here 
    } 

閱讀併發編程指南和每一件事情都解釋得非常清楚。