ICL1901
ICL1901

Reputation: 7778

CocoaTouch - How to stop a loop after switching UIViewControllers?

I am trying to implement a loop that changes the title of buttons and labels (switching languages).

My code is this:

- (void)labelToggle
{
    self.label.text = @" ";
    text = textValue[self.idx]; 
    self.idx++;
    [button setTitle:text forState:UIControlStateNormal];
    self.label.text = textValue[self.idx];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self labelToggle];

    });
}

UPDATE

The loop is called in ViewDidLoad as follows:

textValue= [[NSArray alloc] initWithObjects:@"Add", @"Προσθέστε", nil];
 self.idx = 0;
[self labelToggle];

idx is set here:

- (void)setIdx:(NSInteger)idx
{
    _idx = MAX(0, MIN(idx, idx % [textValue count]));
}

How can I stop the loop when the ViewController is dismissed?

Thanks!

Upvotes: 0

Views: 50

Answers (1)

Danny S
Danny S

Reputation: 1291

You are using recursion here so you are likely to enter in an infinite loop. The best way to achieve what you are trying is to use an NSTimer which calls a selector every X amount of time. Like this:

Declare a timer iVar:

NSTimer *timer;

Start it on viewDidLoad

timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(labelToggle) userInfo:nil repeats:YES];

When you want to stop your toggle you call:

[timer invalidate];
timer = nil;

To stop when the view controller is dismissed it depends on how you are dismissing the view controller, try viewWillDisappear: or viewDidDisappear:, or if your view controller is a modal you are going to call:

    [self dismissViewControllerAnimated:YES completion:^{
        [timer invalidate];
        timer = nil;
    }];

Hope it helps.

Upvotes: 1

Related Questions