如何通过NSThread传递参数

时间:2011-04-05 21:46:27

标签: objective-c multithreading

我之前从未使用过NSThread,我想知道是否有可能将参数传递给它,如果是这样,怎么样?例如:

NSObject *phrase = @"I JUST MADE IT THROUGH TO THE THREAD METHOD!"; 

[NSThread detachNewThreadSelector:@selector (run_thread)
                         toTarget:self 
                       withObject:phrase];

然后


-(void)run_thread
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

NSLog(@"RECORD FILE PATH ---->   %@", phrase);

[pool drain];

 }

我想你知道我在做什么。有什么建议吗?

2 个答案:

答案 0 :(得分:6)

你快到了:

NSObject *phrase = @"I JUST MADE IT THROUGH TO THE THREAD METHOD!"; 

[NSThread detachNewThreadSelector:@selector (run_thread:) // have to add colon
                     toTarget:self 
                   withObject:phrase];

-(void)run_thread:(NSObject* )phrase // change method signature to support taking an NSObject 
{
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

  NSLog(@"RECORD FILE PATH ---->   %@", phrase);

  [pool drain];

}

答案 1 :(得分:1)

[NSThread detachNewThreadSelector:@selector(run_thread:)
                         toTarget:self 
                       withObject:phrase];

-(void)run_thread:(NSString *)phrase
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 

    NSLog(@"RECORD FILE PATH ---->   %@", phrase);

    [pool drain];
}