views:

285

answers:

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!

+1  A: 

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
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
@Yousef you forgot the `:` at the end of the method name.
Dave DeLong
+6  A: 

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
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
`NSNumber` of course... must have been missing coffee :)
Georg Fritzsche