Answer the question
In order to leave comments, you need to log in
A simple timer in Objective C
Hello. I practice in Objective C, many things are not entirely obvious.) Now, it’s not very clear to me that the execution of instructions is not sequential like in other PLs (Python, PHP, Javascript), but, as it were, simultaneous. And you have to go to different tricks. But now it's not about that.
- (IBAction)buttonStartTap:(id)sender {
self.buttonStart.alpha = 0;
for (InstructionModel * instruction in _=self.listOfInstructions){
self.labelInstruction.text = [NSString stringWithFormat:@"%@", instruction.text];
for (int i = 0; i < instruction.duration ; i++){
[NSThread sleepForTimeInterval:1.0f];
self.labelCounter.text = [NSString stringWithFormat:@"%d из %d", i, instruction.duration];
}
}
}
Answer the question
In order to leave comments, you need to log in
It's easier this way:
@interface MyViewController () {
NSTimer *timer;
int seconds;
...
}
@property (weak, nonatomic) IBOutlet UILabel *timerLabel;
@end
...
- (void)viewDidLoad
{
[super viewDidLoad];
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES];
[self.timerLabel setText:@"1:00"]
seconds = 60;
}
- (void)updateTimer:(NSTimer *)theTimer {
if (seconds>0) {
seconds--;
int min = seconds/60;
int sec = seconds%60;
[timerLabel setText:[NSString stringWithFormat:@"%01d:%02d",min,sec]];
} else {
[timer invalidate];
NSLog(@"Timer end");
}
}
Your problem is directly related to your first thesis.
You either call sleepForTimeInterval on the main thread, which completely hangs the user interface, or vice versa, you change the text property of the UI object from the secondary thread, which leads to unpredictable results.
Try using a secondary thread for the sleep loop, and from there change the property by calling performSelectorOnMainThread.
And in general, google on the topic of flows, it is simply necessary to understand.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question