Change NSTimer Interval to Repeat Timer

I am running mainLoop in Cocoa using NSTimer configured as follows:

        mainLoopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/fps target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:mainLoopTimer forMode:NSEventTrackingRunLoopMode];

When I run the program, I set the timeInterval value to 0.0, so that mainloop runs as quickly as possible. In any case, I would like to provide a function to set the frame rate (and therefore the timer time interval) to a specific value at runtime. Unfortunately, as far as I know, this means that I have to reinitialize the timer, since Cocoa does not provide a function like setTimerInterval, This is what I tried:

    - (void)setFrameRate:(float)aFps
{
    NSLog(@"setFrameRate");
    [mainLoopTimer invalidate];
    mainLoopTimer = nil;

    mainLoopTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/aFps target:self selector:@selector(mainloop) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:mainLoopTimer forMode:NSEventTrackingRunLoopMode];
}

but this causes the following error and stops mainloop:

2010-06-09 11:14: 15.868 myTarget [7313: a0f] setFrameRate 2010-06-09 11:14: 15.868 myTarget [7313: a0f] * __NSAutoreleaseNoPool(): 0x40cd80 __NSCFDate - 2010-06-09 11:14: 15.869 myTarget [7313: a0f] * __NSAutoreleaseNoPool(): 0x40e700 NSCFTimer - 0.614628

, "", . , NSTimer ?

!

+5
3

, ! !

, NSTimes , . , .

"BOOL keepOn;" .

-(IBAction)doSomething:(id)sender
{
    // Any action to throw every interval.
}

-(IBAction)switchAutoLoad:(id)sender
{
    if([autoLoad state] == NSOffState)
    {
        NSLog(@"auto-reload on!");

        self performSelector:@selector(fireTimer) withObject:nil afterDelay:0];
        keepOn = YES;
        [autoLoad setState:NSOnState];
    }
    else
    {
        NSLog(@"auto-reload off!");
        keepOn = NO;
        [autoLoad setState:NSOffState];
    }
}

-(void)fireTimer
{
    [self doSomething:nil];

    float theTime = 20; // This is the time interval.

    if(keepOn)
    {
        [self performSelector:@selector(fireTimer) withObject:nil afterDelay:theTime];
    }
}

() bis , "" , . , :)) ( ).

, , .

.

+3

mainLoopTimer.
, , runloop .
, : , , runloop .
.

EDIT: , , , , . , AutoreleasePool . main():

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

.

Autorelease.

0

.

[yourOldTimer invalidate];
yourOldTimer = nil;

.

-2

All Articles