Reputation: 211
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! :-)
Upvotes: 19
Views: 18607
Reputation: 3109
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")
}
Upvotes: 0
Reputation: 36447
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
}
Upvotes: 0
Reputation: 6679
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.
Upvotes: 5
Reputation: 163238
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..
}
Upvotes: 43