开发者

How can I make a counter?

开发者 https://www.devze.com 2023-02-28 16:18 出处:网络
How can I make a counter from 0 to 开发者_运维问答10 choosing the delay?you need to use NSTimer,

How can I make a counter from 0 to 开发者_运维问答10 choosing the delay?


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 
}


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];
}


The method [performSelector: withObject: afterDelay] of the NSObject class is normally used for timed operations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号