Eric Brotto
Eric Brotto

Reputation: 54271

How to pass an argument through NSThread

I've never used NSThread before and I was wondering if it was possible to pass arguments into it and if so, how? For example:

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

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

then


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

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

[pool drain];

 }

I think you see what I'm trying to do. Any advice?

Upvotes: 0

Views: 3276

Answers (2)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

[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];
}

Upvotes: 1

Alex
Alex

Reputation: 66012

You're almost there:

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];

}

Upvotes: 6

Related Questions