2012-06-20 38 views
0

我有一個方法(我們稱之爲運行):在Cocoa的線程上發出循環信號的最佳方式是什麼?

- (void)run 
{ 
    // Do some initialisation 

    // Loop until another thread signals it to exit 
    while (SHOULD_STILL_LOOP) { ... } 

    // Clean up code 
} 

而且我把它叫做:

[self performSelectorInBackground:@selector(run)]; 

什麼是實現SHOULD_STILL_LOOP的最佳方式?我應該使用原子屬性,NSCondition,調度信號量嗎?

也許有些堆棧可以給我一些建議?

謝謝。

回答

0

我發現了一種這樣做的方法,那就是使用NSThread。

- (void)run:(id)obj 
{ 
    while(![[NSThread currentThread] isCancelled]) { ... } 
} 

- (void)start 
{ 
    self.thread = [[NSThread alloc] initWithTarget:self 
              selector:@selector(run) 
              object:self.object]; 
    [self.thread start]; 
} 

- (void)stop 
{ 
    [self.thread cancel]; 
    self.thread = nil; 
} 
相關問題