IOS - Creating & Using Interval Specific Timers
Asked Answered
U

4

19

I am a newbie IOS developer, but I have a good amount of experience in Android development. My question is regarding the creating and use of interval specific timers.

In android I could easily make a timer like this:

timedTimer = new Timer();
    timedTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {

            TimedMethod();
        }

    }, 0, 1000);

Where the interval is 1000 MS and the method TimedMethod() is called on every tick. How would I go about implementing a similar function in IOS?

Thanks so much for reading! Any help at all would be great! :-)

Underwear answered 10/8, 2011 at 0:3 Comment(0)
N
43

You can use a repeating NSTimer like so:

- (void) startTimer {
   [NSTimer scheduledTimerWithTimeInterval:1 
                                    target:self 
                                  selector:@selector(tick:) 
                                  userInfo:nil
                                   repeats:YES];
}

- (void) tick:(NSTimer *) timer {
   //do something here..

}
Noonberg answered 10/8, 2011 at 0:6 Comment(0)
S
5

Use

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

In the same class as you called the above method, create a method called timerCallback. This will be called every time your timer fires; every 1000 milliseconds.

Sumptuary answered 10/8, 2011 at 0:8 Comment(0)
E
0

Use below method present in NSTimer.h file of Foundation Framework

Syntax :

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

Usage :

#define kSyncTimerLength 4 //Declare globally
-(void) timerActivityFunction; //Declare in interface

[NSTimer scheduledTimerWithTimeInterval:kSyncTimerLength target:self
        selector:@selector(timerActivityFunction) userInfo:nil repeats:NO];

-(void) timerActivityFunction {
     // perform timer task over-here   
}
Extensometer answered 10/8, 2011 at 0:3 Comment(0)
D
0

For Swift:

Create a timer object using below line which will call upload method every 10 second. If you get does not implement methodSignatureForSelector extend your class with NSObject. Read this for more information Object X of class Y does not implement methodSignatureForSelector in Swift

 timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: "upload", userInfo: nil, repeats: true)

func upload() {
        print("hi")
    }
Depth answered 8/2, 2016 at 14:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.