2011-01-24 57 views
0

頁眉:實例變量停止正在運行的線程

@interface CodeTest : NSObject { 
BOOL cancelThread; 
} 

-(void) testCode; 
-(void) stopRunning; 
-(void) startRunning; 

@property (assign) BOOL cancelThread; 
@end 

實現:

-(void)stopRunning{ 
    self.cancelThread = YES; 
} 

-(void)startRunning{ 
    self.cancelThread = NO; 

    [NSThread detachNewThreadSelector:@selector(testCode) toTarget:self withObject:nil]; 

} 
-(void)testCode{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    NSLog(@"STARTED"); 
    /* Std C99 code */ 
    while(conditions){ 
      if(self.cancelThread){ 
       conditions = NO; 
      } 
      ... 
      ... 
    } 
    /* end of C code */ 
    [pool release]; 
} 

正如你可以看到,它的輪胎在一個單獨的線程中執行testCode和使用cancelThread BOOL爲停止執行標誌在單獨的線程中。

我有以下問題:

  • 編譯器的信號是self.cancelThread在STD C代碼的中間是無效的(沒有定義個體經營)。我認爲,它試圖將該語句解釋爲c代碼,但這是obj-c。

有什麼缺失?

更新:它與您建議的其中一個人失去{}有關......無需if(self.cancelThread){ conditions = NO; },代碼完美工作。

+0

你不會在`@property(assign)BOOL cancelThread;`?我不認爲是這個解決方案,但你需要`@property(nonatomic)BOOL cancelThread`並在`testCode`方法中設置你的autorelease池。 (不包括NSThread調用) – nacho4d 2011-01-24 14:29:56

+3

@ nacho4d實際上,在這種情況下,您可能*不希望「非原子」,因爲該值正在被多個線程設置/檢查。您在`testCode`方法內部執行autorelease池是正確的。 – 2011-01-24 14:33:05

回答

3

- [CodeTest setCancelThread:]:無法識別的選擇器。

表示您沒有爲cancelThread屬性定義setter。你錯過

@synthesize cancelThread; 

(在你的@implementation節)

1

你所說的 「/ *標準C99代碼* /」 意思?

如果該代碼真的被編譯爲C99代碼,那麼self.cancelThread是有問題的,因爲它是一個Objective-C表達式。首先,這是相當於[self cancelThread], a method call and, secondly, it requires self`這不會出現在C99函數的主體中。

但是,鑑於您所展示的代碼在方法中使用了該代碼,評論沒有意義。