2

I'm still new to Objective C syntax, so I might be overcomplicating this, but I can't seem to figure out how to pass an NSTimeInterval to a thread.

I want to initiate a thread that sleeps for x seconds parameter sent from main thread as follows:

[NSThread detachNewThreadSelector:@selector(StartServerSynchThread) toTarget:self withObject:5];

- (void) StartServerSynchThread:(NSTimeInterval *)sleepSecondsInterval {

    [NSThread sleepForTimeInterval:sleepSecondsInterval];

}

But the compiler keeps giving me a syntax error. I'm not sure exactly how it should be done. Any help would be appreciated. Thanks!

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
Yousef
  • 21
  • 1
  • 2

2 Answers2

12

This is almost exactly the same as @Georg's answer, but using the proper types. :)

If you box the NSTimeInterval into an NSNumber (a subclass of NSValue), you can pass that in instead:

[NSThread detachNewThreadSelector:@selector(startServerSynchThread:) 
                         toTarget:self 
                       withObject:[NSNumber numberWithDouble:myTimeInterval]];

- (void) startServerSynchThread:(NSNumber *)interval {
  [NSThread sleepForTimeInterval:[interval doubleValue]];
}
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • Perfect! I like this solution better as it is more clear to what the method's arguments do. Also the run time error got fixed with the colon (:) after the method name "@selector(startServerSynchThread:". Thanks Dave! – Yousef Jun 20 '10 at 16:36
2

The object parameter has id type, which means only class-type objects can be passed. Integers, like the 5 you are trying to pass, as well as NSTimeInterval (actually just a typedef for double), are fundamental types, not class-types.

You can use NSNumber as a wrapper or pass a NSDate instead.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
  • Thanks for the quick reply, but the NSDate option seems a lot like a hack to me. Would you be kind enough to post the NSValue solution? Also when I tried running the above code, I got a run time error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[MainScreenController StartServerSynchThread])' – Yousef Jun 20 '10 at 16:20
  • @Yousef you forgot the `:` at the end of the method name. – Dave DeLong Jun 20 '10 at 16:28