M
M
Maxim2014-05-31 22:53:11
Objective-C
Maxim, 2014-05-31 22:53:11

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];
        }
    }
}

Actually what I have. ListOfInstructions array, each array object has properties; NSString * text, and int duration. I iterate over the array and change the text of the label along the way, each label retains its text for the number of seconds indicated in duration.
But that's bad luck, the text does not change.) Although NSLog shows that the enumeration of the array is in progress. It's probably some kind of feature.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
ManWithBear, 2014-05-31
Rumoynikov @RUQ

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

A
agee, 2014-06-05
@agee

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 question

Ask a Question

731 491 924 answers to any question