Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

faroZ06

macrumors 68040
Original poster
Apr 3, 2009
3,387
1
I'm playing around in Objective-C with a "foundation tool" (Objective-C command line utility) project in Xcode. At the end of my program, it's supposed to go to a clock that updates itself in the Terminal window. The problem is that it doesn't start on the right time, so it's almost always off by a fraction of a second. I tried to fix that by having it wait until the nanosecond time is a multiple of 10^9, but this ends up just going into infinite loop. What am I doing wrong, and is there a better way (I'm guessing there is)?

double nano = 1111111111111;
while (fmod(nano, 1000000000) != 0){
nano = [NSDate timeIntervalSinceReferenceDate];
}
//This while loop waits for the nanoseconds to be divisible by 10^9.
while (true){
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:mad:"dd-MM-yyyy HH:mm:ss"];

dateString = [formatter stringFromDate:[NSDate date]];
printf([dateString UTF8String]); printf("\n");
sleep(1); // or usleep(3000000);
system("clear");
}
 
Last edited:
I'm playing around in Objective-C with a "foundation tool" (Objective-C command line utility) project in Xcode. At the end of my program, it's supposed to go to a clock that updates itself in the Terminal window. The problem is that it doesn't start on the right time, so it's almost always off by a fraction of a second. I tried to fix that by having it wait until the nanosecond time is a multiple of 10^9, but this ends up just going into infinite loop. What am I doing wrong, and is there a better way (I'm guessing there is)?

[NSDate timeIntervalSinceReferenceDate] measures the time interval in seconds.

And to avoid wasting CPU time, call [NSDate timeIntervalSinceReferenceDate] once, round up to the next second by calling ceil (), then call usleep for waiting the right amount of time.
 
[NSDate timeIntervalSinceReferenceDate] measures the time interval in seconds.

And to avoid wasting CPU time, call [NSDate timeIntervalSinceReferenceDate] once, round up to the next second by calling ceil (), then call usleep for waiting the right amount of time.

Ah, thanks. Sorry for the noob question.
 
Ah, thanks. Sorry for the noob question.

Nothing to be sorry about. You posted the code that caused the problem, which means you gave the information that was needed to find the cause of the problem - that puts you far ahead of the average.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.