Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NStimer -- what am I doing wrong here?

Tags:

cocoa

iphone

I've been using an NSTimer successfully, but am now having trouble with it. Undoubtably something stupid. Appreciate another set of eyes. Running the debugger, I see that applicationDidFinishLaunching is called, but trigger is never called.

-(void) trigger:(NSTimer *) theTimer{
    NSLog(@"timer fired");
}

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    nst = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(trigger) userInfo:nil repeats:YES];

    [window makeKeyAndVisible];
}
like image 805
morgancodes Avatar asked Feb 07 '10 21:02

morgancodes


2 Answers

The selector must have the following signature:

- (void)timerFireMethod:(NSTimer*)theTimer

so you need

@selector(trigger:)

--edit--

Maybe you are doing this somewhere else, but in the code you included you do not actually start the timer. You have to add it to a NSRunLoop before it can trigger any events at all.

 [[NSRunLoop currentRunLoop] addTimer:nst forMode:NSDefaultRunLoopMode];

If I read the examples correctly. I've only used the one the init method that automatically adds it to the current NSRunLoop. You really should look at the developer docs that someone included in the comments to my post.

like image 104
willcodejavaforfood Avatar answered Nov 02 '22 22:11

willcodejavaforfood


Two things:

1) as others say, the method should have the following signature..

-(void) trigger:(NSTimer *) theTimer;

and you make the timer thus:

nst = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(trigger:) userInfo:nil repeats:YES];

2) merely creating the timer does not run it. As the documentation says:

You must add the new timer to a run loop, using addTimer:forMode:. Then, after seconds have elapsed, the timer fires, invoking invocation. (If the timer is configured to repeat, there is no need to subsequently re-add the timer to the run loop.)

Here's a piece of real functioning code that you can model after. The timer creation is the same as yours, but it also adds it to runloop the right way.

[[NSRunLoop currentRunLoop] addTimer:
     [NSTimer timerWithTimeInterval:0.1
                             target:self
                           selector:@selector(someSelector:)
                           userInfo:nil
                            repeats:NO]
                                 forMode:NSDefaultRunLoopMode];
like image 34
Jaanus Avatar answered Nov 02 '22 23:11

Jaanus