@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; }
,代码完美工作。
你不会在`@property(assign)BOOL cancelThread;`?我不认为是这个解决方案,但你需要`@property(nonatomic)BOOL cancelThread`并在`testCode`方法中设置你的autorelease池。 (不包括NSThread调用) – nacho4d 2011-01-24 14:29:56
@ nacho4d实际上,在这种情况下,您可能*不希望“非原子”,因为该值正在被多个线程设置/检查。您在`testCode`方法内部执行autorelease池是正确的。 – 2011-01-24 14:33:05