Create a timer (Nstimer)
- (void)viewDidLoad { [super viewDidLoad]; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actionTimer:) userInfo:nil repeats:YES];}- (void)actionTimer:(NSTimer *)timer{}
Nstimer is run by default mode, and Defaults mode almost includes all input sources (except Nsconnection) Nsdefaultrunloopmode mode.
The Actiontimer method is called once every 1s. Nstimer is not very simple to use. This is a relatively elementary application of Nstimer.
Nstimer fails when the main interface is sliding
What does it mean that the main interface is being slid? This means that the main interface has UITableView or uiscrollview, sliding uitableview or Uiscrollview. At this time the Nstimer failed.
Let's write a demo, start the timer on a UITableView uiviewcontroller, add 1 for each 1s number, and display the number on the Uilabel.
- (void)viewDidLoad { [super viewDidLoad]; [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actionTimer:) userInfo:nil repeats:YES];}- (void)actionTimer:(NSTimer *)timer{ self.number++; self.label.text = [NSString stringWithFormat:@"%d",self.number]; NSLog(@"%d",self.number);}
About the creation of UITableView and Uilabel I omitted. Detailed code can be downloaded here: Iosstrongdemo,iosstrongdemo I'll keep updating, and we'll get a star on GitHub.
This way, when the user drags the UITableView in Uitrackingrunloopmode, the Nstimer fails and cannot fire. The number on the Self.label cannot be updated.
Modify Nstimer's Run loop
The workaround is to add it to Uitrackingrunloopmode mode or Nsrunloopcommonmodes mode.
[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
Or
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Nsrunloopcommonmodes: is a collection of patterns that, when bound to a collection of events, is the equivalent of binding to each pattern within the collection.
Code:: Iosstrongdemo
The source of this article just online: http://www.superqq.com/blog/2015/07/10/ioskai-fa-zhi-nstimershi-yong-chu-tan/
On the use of Nstimer in iOS development