views:

469

answers:

4

I am communicating with a webservice to retrieve a numerical value that comes into my function as an NSString. This number tells me the precise amount of time to wait until I perform another action, and it is critical that it be precise.

As an example, if the string is "89283", then this means I must wait 89.283 seconds. So I'd like to know the best way in Objective-C for iPhone to convert this string to a precise value that I can pass to the performSelector:afterDelay: function. Here's my sample code, but I'm guessing its not accurate.

NSString *myDelayString = @"89283";
int myDelay = [myDelayString intValue]/1000;
[self performSelector:@selector(myFunction) withObject:nil afterDelay:myDelay];

I think the myDelay value really should be a NSTimeInterval, but I'm not sure how to make that from the string I have. Thanks in advance.

+1  A: 

NSTimeInterval is a double, and you're doing integer division. Just change its type from int to double and you should be good.

Dave DeLong
NSTimeInterval is a double...
Jason Coco
@Jason - touché. i should probably verify that what i'm posting is correct before i actually hit "Submit", eh?
Dave DeLong
A: 

don't have enough rep to just add a comment but make sure if you convert myDelay to float that you divide by 100.0 otherwise you won't get what you expect.

John Stallings
+4  A: 

Here is the code with changes to allow double precision.

NSString *myDelayString = @"89283";
NSTimeInterval myDelay = [myDelayString doubleValue]/1000;
[self performSelector:@selector(myFunction) withObject:nil afterDelay:myDelay];

Use doubleValue in order to get the string as a double so you can avoid integer division. NSTimeInterval's type is defined as a double on the iphone, so you can store the double result into it and then pass it to the afterDelay: part of the selector.

Brandon Bodnár
Thanks to everyone for the great answers. Really appreciate the support here.
hookjd
+1  A: 

Delays using run loops, as you are, or with NSTimer are very inaccurate because you must always wait for the previous event to be fully processed. When executing, your code could be running 100ms or more later than you expect.

So despite your high precision, the accuracy will likely be seriously lacking.

Depending on why you need this precise timing, you may be able to make corrections to your calculations and render the difference moot.

Steve Weller