Creating a real-time clock in an iOS update using NSTimer or performSelector?

I want to display the real time in the label, and I found two approaches for updating NSDate :

The performSelector approach:

 - (void)viewDidLoad { [super viewDidLoad]; [self updateTime]; } - (void)updateTime { NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"hh:mm:ss"]; label.text = [dateFormat stringFromDate:[NSDate date]]; //call updateTime again after 1 second [self performSelector:@selector(updateTime) withObject:self afterDelay:1.0]; } 

NSTimer approach:

 - (void)viewDidLoad { [super viewDidLoad]; Timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; } - (void)updateTime { NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"hh:mm:ss"]; label.text = [dateFormat stringFromDate:[NSDate date]]; } 

Which one is the best, more efficient and reliable method?

+4
source share
2 answers

Firstly, it is not entirely related to Xcode.

Secondly: more productively? Really? When is it called once per second? Just forget to worry about efficiency.

Thirdly, they are equivalent, but I do not see the need for recursive self-calculus of a method. Just go with NSTimer , which is why it was invented.

+4
source

The timer does its best to execute a “fixed” schedule, that is, every second.

On the other hand, a call to performSelector:afterDelay at the end of a function that was executed, say, 500 ms to execute, will cause the function to be called every 1500 ms (500 ms that were required to execute + 1 s delay).

Thus, the timer is more reliable. As H2CO3 said, forget about performance, this is not a problem with such simple tasks.

+1
source

Source: https://habr.com/ru/post/1487887/


All Articles