2011-01-24 56 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函数的主体中。

但是,鉴于您所展示的代码在方法中使用了该代码,评论没有意义。