bredmann
bredmann

Reputation: 1

Alternative delay function

I use the following code to delay changing text:

int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     label.text = %"ye";}

I can't cancel this function, so if I dismiss my viewController by clicking "Back" and instantly open it again, the function will change the text. How can I rework this to allow cancelation?

Upvotes: 0

Views: 52

Answers (2)

Khanh Nguyen
Khanh Nguyen

Reputation: 11132

self.cancelled = NO; // cancelled is a BOOL property

int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    if (!self.cancelled) {
        label.text = %"ye";
    }
}

...

// When back is tapped
self.cancelled = YES;

Upvotes: 0

tomahh
tomahh

Reputation: 13661

self.timer = [NSTimer scheduledTimerWithTimeInterval:delayInSeconds
                                              target:self
                                            selector:@selector(updateLabel)
                                            userInfo:nil
                                             repeats:NO];


- (void)updateLabel
{
   self.label.text = %"ye";
}

and in your viewWillDisapear:

[self.timer invalidate];

Upvotes: 5

Related Questions