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

0

4 Answers 4

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

}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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   
}

Comments

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")
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.