Ios 如何以编程方式在NSTimer间隔内实现增加

Ios 如何以编程方式在NSTimer间隔内实现增加,ios,objective-c,Ios,Objective C,我和许多其他人在数学上有一个问题,导致函数被调用的次数越来越多。我的目标是越来越频繁地调用if语句中的代码。该函数每隔.01秒调用一次。我希望它第一次运行是在1秒,然后越来越快,直到大约.3为止。我需要知道在盒子里放什么 NSTimer每隔.01秒调用一次该函数 代码是: -(IBAction)redmaker:(id)sender{ refreshrate = refreshrate+1; if(SOMETHING){ int rand =arc4rando

我和许多其他人在数学上有一个问题,导致函数被调用的次数越来越多。我的目标是越来越频繁地调用if语句中的代码。该函数每隔
.01
秒调用一次。我希望它第一次运行是在
1
秒,然后越来越快,直到大约
.3
为止。我需要知道在盒子里放什么

NSTimer每隔.01秒调用一次该函数

代码是:

-(IBAction)redmaker:(id)sender{
    refreshrate = refreshrate+1;

    if(SOMETHING){

        int rand =arc4random() %65;
        UIButton *button = (UIButton *)[self.view viewWithTag:rand];
        button.backgroundColor = [UIColor colorWithRed:255 green:0 blue:0 alpha:1];
        button.enabled = YES;
        deathtimes[rand] = 10;
        rate = rate+1;
        refreshrate = 0;

    }

您应该使用
NSTimer
调用您的方法。在头文件中定义一个
NSTimer

h班

NSTimer *timer;
double interval;
m班

//put the following two lines in viewDidLoad, or some other method
interval = 1.0
timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(redmarker:) userInfo:nil repeats:NO];

-----

//put this at the bottom of your if statement

if (interval > 0.3)
{
    [timer invalidate];

    //change this value to something greater to call the method faster
    interval -= 0.05;

    timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(redmarker:) userInfo:nil repeats:NO];
}

您可能会遇到导致游戏速度减慢的问题。如果出现这种情况,则主线程可能无法同时处理计时器、按钮和其他操作。您将需要研究使用大中央调度。

重复计时器始终使用相同的时间间隔。你不能改变它

如果希望计时器的间隔逐渐缩短,请创建一个非重新绘制计时器,该计时器在每次触发时都会使用相同的选择器触发一个新计时器。使用实例变量来保存间隔,并在每次激发时从间隔值中减去一些值


至于您的“if(SOMETHING)”,没有其他人可以告诉您代码中决定要做什么的条件。

您不能将Grand Central Dispatch与如下递归方法结合使用:

#import "ViewController.h"

@interface ViewController ()
{
    CGFloat fireTime;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    fireTime = 1.0;

    // initial call to method
    [self foo];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)foo
{
    NSLog(@"Hello at, timer fired off after %lf", fireTime);

    if (fireTime > 0.3)
    {
        // decrement timer
        fireTime -= 0.1;
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(fireTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self foo];
    });
}

@end