【问题标题】:Set up a temporary timer iOS [duplicate]设置一个临时计时器iOS [重复]
【发布时间】:2012-09-02 06:08:19
【问题描述】:

可能重复:
How to make a periodic call to a method in objective c?

我正在制作一个应用程序,当用户触摸屏幕时,会调用以下方法:

- (void)explode:(int)x

用户只需触摸屏幕一次,但我希望该方法每 0.1 秒重复调用 100 次,然后停止调用。

有没有办法在传递整数的方法上设置像这样的“临时”计时器?

【问题讨论】:

  • 是的,有几种方法,只要你稍加努力,就会发现它们。

标签: objective-c ios cocoa-touch methods timer


【解决方案1】:

您可以将计数器和“x”传递到计时器的用户信息中。试试这个:

在捕获触摸事件的方法中创建计时器并将计数器和 int 'x' 传递给 userInfo:

NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] initWithCapacity:2];
[userInfo setValue:[NSNumber numberWithInt:x] forKey:@"x"];
[userInfo setValue:[NSNumber numberWithInt:0] forKey:@"counter"];

[NSTimer timerWithTimeInterval:0.1
                        target:self
                      selector:@selector(timerMethod:)
                      userInfo:userInfo
                       repeats:YES];

创建定时器方法,查看userInfo的计数,100次后定时器失效:

- (void)timerMethod:(NSTimer *)timer
{
    NSMutableDictionary *userInfo = timer.UserInfo;
    int x = [[userInfo valueForKey:@"x"] intValue];

    // your code here

    int counter = [[userInfo valueForKey:@"counter"] intValue];
    counter++;

    if (counter >= 100)
    {
        [timer invalidate];
    }
    else
    {
        [userInfo setValue:[NSNumber numberWithInt:x] forKey:@"x"];
        [userInfo setValue:[NSNumber numberWithInt:counter] forKey:@"counter"];
    }

}

另请参阅NSTimer 上的 Apple 文档:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

【讨论】:

  • 如我在问题中所说,将整数“x”传递给方法怎么样?
  • 是的,如果您愿意,您可以通过计时器的 userInfo 传递它。请参阅上面我编辑的答案。
  • 是的,所以 userInfo 实际上应该是一本字典...请参阅上面的修订答案以获得更好的实践...
猜你喜欢
  • 2011-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多