I need a timer (stopwatch)

jazz

Registered
Does anyone know how to can use a stopwatch timer in cocoa? I want to be able to stop, start, and reset it. From what I have read about NSTimer, it does not do what I want.

Thanks
 
just set the timer to fire at whatever granularity you want your stopwatch to operate at, and set repeats to YES. NSTImeInterval is a double, so you could do

timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:yourControllerInstance selector:mad:selector(timerFired:) userInfo:yourExtraInfo repeats:YES];

that would fire every 1/10th of a second. you can then update your stopwatch in your timerFired: method. if you want to stop it, just do a [timer invalidate]. if you want t start it again, recreate it the same as before.
 
hahaha, that smiley should not be in the middle of that call. its supposed to be a : and a ). sheesh.
 
i am not sure i understand this correctly.
let me try and piece this together.
first, i declare the timer:
NSTimer timer;
right? then, i can start the timer, i guess.
Timer = [NSTimer scheduledTimerWithTimeInteraval:0.1 selector:??? target:doINeedOne??? userInfo:???

but, then how do i get the double value? Can a overload it by
double totalTime=timer;
??

All i want to do is start the timer, and let it go. I don't want to affiliate it with any functions or processes. I just want to be able to start the timer, and when my app does what it wants to do, or when i choose, have to timer stop and return the time elapsed.

Sorry if i sound like i don't know what i am talking about. I know obj-c and c++ very well, but i am just learning cocoa.

Thanks,
-Jazz
 
Then you don't want a timer. Just remember the start time. When you want to know the elapsed time, then look up the current time. Then subtract them to get the difference.

NSDate objects can do this automatically, although you should check that they give subsecond precision.
 
Well, time returns a long of the number of milliseconds since startup, so you can subtract the two longs and divide by 1000 to get seconds, including fractional part. To use this in your code,

long starttime = system("time");
// .... do some stuff
long endtime = system("time");
long elapsedtime = endtime - starttime;
float elapsedseconds = elapsedtime / 1000.f;

or whatever works. There is probably a pure Cocoa way -- search the documentation for something -- but this is a pure Unix way, so maybe just as good. In Java you can use System.getCurrentTimeMillis(). Did you check that NSDate objects don't include the fractional parts of seconds, though?
 
ya, i want to do it in cocoa if possible. it must be. i can get seconds using NSDate, but i would really like at least tenths of a second. Here is the code for seconds.

NSDate *startTime = [NSDate date];
//some stuff that takes time to do
NSDate *endTime = [NSDate date];
NSTimeInterval elapsedTime = [endTime timeIntervalSinceDate:(NSDate *)startTime];

does anyone know how to do tenths?
 
Back
Top