【问题标题】:If I want to execute a method every x seconds y times, should I use NSTimer?如果我想每 x 秒 y 次执行一个方法,我应该使用 NSTimer 吗?
【发布时间】:2013-03-14 18:13:17
【问题描述】:

我想让不同的东西每 2 秒出现 10 次。我将如何在 Objective-C 中实现这一目标?

我正在考虑使用 NSTimer 并在这么多秒后使其无效,就像在上面的示例中,在我启动计时器后 2 * 10 秒。或者有没有办法测量蜱虫?

或者我正在考虑使用 for 循环并使用 performSelector:withDelay: 方法。

哪个更好?

【问题讨论】:

  • 使用重复计时器。还有一个类属性,它是一个整数,用于跟踪你的计时器被调用了多少次。

标签: ios objective-c ios5 ios6 nstimer


【解决方案1】:

使用NSTimer并将时间interval设置为2 seconds,将repeats设置为YES

计算它触发的次数。 Invalidate 到了 10 就这样了

代码:

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(trigger:) userInfo:yourObject repeats:YES];

- (void)trigger:(NSTimer *)sender{

    id yourObject = sender.userInfo;

    static int count = 1;

    @try {

        NSLog(@"triggred %d time",count);

        if (count == 10){

            [sender invalidate];
            NSLog(@"invalidated");
        }

    }
    @catch (NSException *exception)
    {
        NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
    }
    @finally {

        count ++;
    }
}

【讨论】:

  • 我是否计算在我调用的方法中触发的次数?当它达到该限制时,我如何使其失效?
  • 我已经添加了方法...请检查一下'
  • 如果我想根据使用情况将 10 更改为不同的数字怎么办。我可以为方法设置参数吗?
  • 是的,通过 NSTimer UserInfo 传递。我现在已经编辑了答案。请检查一下
【解决方案2】:

我使用了你的第二个选项,不需要计时器

for (int a=0; a<10; a++) {
    [self performSelector:@selector(print) withObject:nil afterDelay:2.0*a];
}


-(void)print
{
    NSLog(@"sth");
}

您可以使间隔和重复计数灵活。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多