2011-05-17 81 views
0

到目前爲止,我的應用程序非常簡單,但現在我發現我需要在單獨的線程上運行進程,所以這是一個xCode 101問題,問我該怎麼做那。新手問題關於在新線程上運行進程

我想運行應用程序啓動時運行的進程,所以我想在AppDelegate.applicationDidFinishLaunching中執行它。

從我讀過的內容中,我認爲這是我需要做的,但如果我錯了,請糾正我。

// *** AppDelegate.m **** 

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

    [NSThread detachNewThreadSelector:@selector([XMLParser parseXML:]) 
     toTarget:self 
     withObject:requestStr]; 

} 

// *** XMLParser.m *** 

-(void)parseXML { 

    // Dunno why NSAutoreleasePool is needed but apparently it is 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // . . . my code 

    [pool release]; 

} 


} 

回答

1

我認爲有一些問題,@selector希望選擇器不是方法調用。所以,正確的應該是這樣的

- (void)applicationDidFinishLaunching:(UIApplication *)application { 

    [NSThread detachNewThreadSelector:@selector(parseXML:) 
     toTarget:objXMLParser 
     withObject:requestStr]; 

} 

//here the taget is the object whose selector you are passing. so you can't use self there as parseXML: is the method of XMLParser class 

// *** XMLParser.m *** 

-(void)parseXML { 

    // Dunno why NSAutoreleasePool is needed but apparently it is 

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    // . . . my code 

    [pool release]; 

} 

//自動釋放池需要的,因爲它是一個獨立的線程,你的代碼可能會使用一些可可或您自己的呼叫/方法/代碼,自動釋放的對象,這就是爲什麼你必須爲那些自動釋放對象保留一個自動釋放池。如果您的代碼沒有使用任何[obj autorelease]語句,或者在這種情況下不自動釋放對象,則可以省略自動釋放池語句,但保留它是個好習慣。

+0

非常感謝您的回覆。 LQ – 2011-05-17 16:13:16

0

我沒有使用過你描述的方法,而是使用了NSOpertaions。它支持併發和非併發操作,並且易於使用。