PDA

View Full Version : NSTimer




liptonlover
Jul 27, 2008, 10:59 PM
I'm trying to learn how to get a timer working... I read the apple docs on timers and loops. I also went through the loop and nstimer class docs. Finally I went through the chapter on NSTimer in cocoa programming for mac os x. Here's my unsuccessful code. (I just checked, all my connections are good. As far as I can tell it should work. Pressing "go" does nothing though...)


#import <Cocoa/Cocoa.h>

@interface AppController : NSObject/* Specify a superclass (eg: NSObject or NSView) */ {
IBOutlet id progressBar;
NSTimer *timer;
int count;
}
- (IBAction)go:(id)sender;
- (IBAction)reset:(id)sender;
- (IBAction)stop:(id)sender;
@end


#import "AppController.h"

@implementation AppController
- (IBAction)go:(id)sender {
timer=[[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(increment:) userInfo:nil repeats:YES] retain];
}

- (IBAction)reset:(id)sender {

}

- (IBAction)stop:(id)sender {

}

- (void)increment:(NSTimer *)aTimer {
count=count+1;
[progressBar setIntValue:count];
}
@end

Can anyone tell me what's wrong? Thanks! Nate



Darkroom
Jul 28, 2008, 12:15 AM
not totally sure about this, but what exactly is "count"?

kpua
Jul 28, 2008, 12:57 AM
NSProgressIndicator is not an NSControl, so there is no setIntValue: method. You need to use incrementBy: or setDoubleValue: after you set up a min-max range in IB or setMinValue: and setMaxValue:

Also, FYI, a couple more things: You're leaking your NSTimer, since it's never released anywhere, and you probably want to prevent multiple timers from being created in your go: method. (A simple timer == nil check will work.)

HiRez
Jul 28, 2008, 02:21 AM
kpua is probably right, but the simple thing to do (for starters) would be to throw a couple NSLog statements in your go: and increment: methods to see if they are getting called at all. I probably use NSLog as my primary debugging method about 90% of the time. Primitive, yes, but it works.

liptonlover
Jul 28, 2008, 08:05 AM
@darkroom - count is simply an int, hence this line:
int count;

@kpua - Thanks I forgot about that... I used them before. I know I'm leaking, I just didn't bother with that bit of code yet. I want to get it working first. Thanks for pointing that out though :)

@hirez - ok thanks :)

HiRez
Jul 28, 2008, 12:24 PM
Also, your app may have stopped responding because of a runtime error. Are you looking at the console while it's running?