RollRoll
RollRoll

Reputation: 8462

NSTimer not working calling UIButton setHidden:YES/NO

I can't understand why this doesn't work. I'm trying to display lblstatus when the timer cycle is hit:

-(void) viewDidAppear:(BOOL)animated
{
        [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(TimeForPictureCycle)
                                       userInfo:nil
                                        repeats:NO];
}

-(void)TimeForPictureCycle
{
    while(YES)
    {
        [lblStatus setHidden:NO];
        sleep(2);
        [lblStatus setHidden:YES];
        sleep(3);
    }
}

Upvotes: 0

Views: 329

Answers (2)

rdelmar
rdelmar

Reputation: 104082

You can do it simply with:

-(void)viewDidAppear:(BOOL)animated {
    [lblStatus performSelector:@selector(setHidden:) withObject:0 afterDelay:1];
    [lblStatus performSelector:@selector(setHidden:) withObject:@1 afterDelay:3];
}

I'm not really sure why I can pass 0 as an object, but it works.

Upvotes: 1

Tobi
Tobi

Reputation: 5519

Your calling sleep() on the main thread, that means after you set your label to hidden that thread pauses and prevents the run loop from continuing thus it's not able to update your UI. Your current code simple blocks your whole application.

What you could do is this:

-(void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.showTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                         target:self
                                       selector:@selector(showLabel)
                                       userInfo:nil
                                        repeats:NO];
}

-(void)showLabel
{ 
    [lblStatus setHidden:NO];
    self.hideTimer = [NSTimer scheduledTimerWithTimeInterval:2
                                         target:self
                                       selector:@selector(hideLabel)
                                       userInfo:nil
                                        repeats:NO];
}

-(void)hideLabel
{        
    [lblStatus setHidden:YES];
    self.showTimer = [NSTimer scheduledTimerWithTimeInterval:3
                                         target:self
                                       selector:@selector(showLabel)
                                       userInfo:nil
                                        repeats:NO];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.showTimer invalidate];
    [self.hideTimer invalidate];
}

Upvotes: 3

Related Questions