Re: while loop with sleep(): logging works, but not UI events
Re: while loop with sleep(): logging works, but not UI events
- Subject: Re: while loop with sleep(): logging works, but not UI events
- From: "Shawn Erickson" <email@hidden>
- Date: Sat, 28 Jun 2008 08:51:30 -0700
On Sat, Jun 28, 2008 at 8:29 AM, Shawn Erickson <email@hidden> wrote:
> On Sat, Jun 28, 2008 at 8:13 AM, Daniel Richman
> <email@hidden> wrote:
>> Thanks very much for this detailed explanation. I realize my mistake now; I
>> was thinking about this in the wrong way. I eventually coded it as follows:
>>
>> - (IBAction)startTimer:(id)sender
>> { timeInSeconds = [((NSNumber *)[inTextField objectValue]) intValue];
>> [NSTimer scheduledTimerWithTimeInterval:1.0
>> target:self
>> selector:@selector(checkTimer:)
>> userInfo:nil
>> repeats:YES];
>> }
>>
>>
>> - (void)checkTimer:(NSTimer *)timer
>> {
>> if (timeInSeconds == 0) {
>> [timer invalidate];
>> [outTextField setStringValue:@"Finished timing"];
>> } else {
>> [outTextField setStringValue:[NSString stringWithFormat:@"%d more
>> second(s) to go", timeInSeconds]];
>> NSLog(@"in loop, timeInSeconds is %d", timeInSeconds);
>> timeInSeconds--;
>> }
>> }
>
> You really shouldn't use an NSTimer to count time as you are doing
> above. For example your timer can be delayed from firing because of
> other work taking place on the main thread. Over a long enough period
> of time (use enters a larger value for seconds) these small delays can
> build up and cause you to miscount time when compared to wall clock
> time.
>
> You should instead use something like NSDate. For example create an
> NSDate instance for the finish time (consider +[NSDate
> dateWithTimeIntervalSinceNow:]) in you action method and then in your
> check timer method look at that date to see if you have passed it to
> know if you are done. Also you would use current time and finish time
> to calculate how many seconds remand. You get current time using
> -[NSDate date].
>
> You could also consider two timers... one firing often to cause you to
> update the UI and the other firing once at the finish time.
Ah found it...
http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg00447.html
...and you can count using a timer if you use a constant time based
(see my email related to the linked email thread)...
http://lists.apple.com/archives/cocoa-dev/2006/Nov/msg00494.html
-Shawn
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden