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! :-)

user879702
  • 211
  • 1
  • 2
  • 5

4 Answers4

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..

}
Jacob Relkin
  • 151,673
  • 29
  • 336
  • 313
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.

Benjamin Mayo
  • 6,534
  • 2
  • 23
  • 25
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   
}
Jayprakash Dubey
  • 32,447
  • 16
  • 161
  • 169
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")
    }
Community
  • 1
  • 1
2ank3th
  • 2,280
  • 1
  • 17
  • 33