简体   繁体   中英

How can I make a counter?

如何选择0到10的计数器选择延迟?

Create an NSTimer:

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds 
                                     target:(id)target 
                                   selector:(SEL)aSelector 
                                   userInfo:(id)userInfo 
                                    repeats:(BOOL)repeats;

Yours would probably look like this:

[NSTimer scheduledTimerWithTimeInterval:1.0
                                  target:self
                                selector:@selector(timerFired:)
                                userInfo:nil
                                 repeats:YES];

In the method that is invoked, increment a counter, and check to see if you've hit your count to stop the timer:

- (void)timerFired:(NSTimer *)timer
{
     static int counter = 0;

     // Do Something

     counter++;
     if(counter == 10)
          [timer invalidate];
}

you need to use NSTimer ,

Check the below code as reference.

- (void) startCounter {
     counterCount = 0;
    [NSTimer scheduledTimerWithInterval:0.09f target:self selector:@selector(showElapsedTime:) userInfo:nil repeats:YES];
}

showElapsedTime will be called after delay, you provide.

-(void) showElapsedTime: (NSTimer *) timer {
    counterCount++;
    if(counterCount == 10)
    {
      [timer invalidate];
    }

// Write your code here 
}

NSObject类的方法[performSelector: withObject: afterDelay]通常用于定时操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM