Mac Help with Making a Clock in Objective-C Command Line Utility

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:

gnasher729

macrumors P6
Nov 25, 2005
16,593
3,216
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.
 

faroZ06

macrumors 68040
Original poster
Apr 3, 2009
3,387
1
[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.
 

gnasher729

macrumors P6
Nov 25, 2005
16,593
3,216
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.