NSThread问题如何解决?

时间:2012-04-14 11:07:11

标签: objective-c ios

我正在编写以下代码。

#import <objc/objc.h>
#import <Foundation/Foundation.h>

@interface myT :NSObject
-(void) startT;
-(void) tfun;
@end

@implementation myT 
-(void) tfun
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog (@"Inside thread Function .. ");
[pool drain];
}

-(void) startT
{
  [NSThread detachNewThreadSelector:@selector(tfun) toTarget:self withObject:nil ];
}
@end

int main ( int argc, char ** argv)
{
   myT *t = [[myT alloc] init];
   [t startT];
   return 0;
} 

它编译,并导致运行时错误。我做错了什么?我熟悉pthread。我怎么能等到线程完成,即:pthread_wait kind。

1 个答案:

答案 0 :(得分:0)

您可以旋转运行循环,直到设置完整的标志,如:

-(void) startT
{
   [NSThread detachNewThreadSelector:@selector(tfun) toTarget:self withObject:nil ];

   do {

        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

   } while (!self.completed);
}

在你的tfun方法中

-(void) tfun
{
   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
   NSLog (@"Inside thread Function .. ");
   [pool drain];
   self.complete = YES;
}