运行NSTimer一定次数

时间:2011-11-14 02:48:04

标签: ios nstimer

是否可以像这样运行NSTimer:

NSTimer *f = [[NSTimer alloc] initWithFireDate:[NSDate date]
                                      interval:.05
                                        target:self
                                      selector:@selector(checkForCollisions)
                                      userInfo:nil repeats:YES];

NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:f forMode: NSDefaultRunLoopMode];
[f release];

但是指定我希望它运行的次数?所以,如果我希望它只运行2秒(假设间隔为.05),我可以指定它运行40次?这可能吗?

3 个答案:

答案 0 :(得分:3)

YourViewController.h

NSTimer *f;
NSInteger counter;

YourViewController.m

- (void)setup {
    // initialization code
    counter = 0;
    f = [[NSTimer alloc] initWithFireDate:[NSDate date]
                                 interval:.05
                                   target:self
                                 selector:@selector(checkForCollisions)
                                 userInfo:nil repeats:YES];

    NSRunLoop *runner = [NSRunLoop currentRunLoop];
    [runner addTimer:f forMode: NSDefaultRunLoopMode];
}

- (void)checkForCollisions {
    // handle check

    counter++;
    if (counter >= 40) {
        [f invalidate];
        [f release];
    }
} 

答案 1 :(得分:0)

static int numberOfTimes = 0;
static int inAndOut = 0;
...

int interval = 0.5;
int 2seconds = 120;
numberOfTimes = 2seconds/interval;

- (void) checkForCollisions {
    if (numberOfTimes <= inAndOut) {
        //check collisions
    }
}

答案 2 :(得分:0)

只需减少checkForCollisions方法中的计数器。