a NSTimer in While Loop

2019-08-20 08:18发布

Greeting !!

The following codes are now I am doing :

BOOL bJobDone = NO ;
bBrickDropDone = NO ; //global var here !!
NSTimer* timer = nil ;

while(bJobDone==NO)
{    

    if(timer == nil)
    {
        timer = [NSTimer scheduledTimerWithTimeInterval:0.3
                                                      target:self
                                                    selector:@selector(dropBrick:)
                                                    userInfo:nil
                                                     repeats:YES];
    }
    if(bBrickDropDone==YES)
    {
        bBrickDropDone = NO ;
        [timer invalidate] ;
        timer = nil ;

        if([self MarkBrickBomb]==YES)
        {
            bJobDone = NO ;
            [self dealBomb] ;
            if([self AllClean]==YES)
            {
                bJobDone = YES ;
                igameidx = igameidx + 1 ;
            }
        }else
        {
            bJobDone = YES ;
        }            
    }//if(bBrickDropDone==YES)

}//while bJobDone==NO

As you can see , the timer call dropBrick function once for 0.3 second , if bBrickDropDone is finally = YES (dropBrick function modify this to YES if something happen) it will process another function MarkBrickBomb and goes on until bJobDone=YES,break out of loop!!

I think my code is lousy , I should not check bBrickDropDone flag in the while loop, because it is not efficient , also cost resource a lot !!

I need a timer to get an animated UIImageView switch , buy Still don't like to check the done flag in while loop(it is not good ,I think) , so what can I do in this case ? Can I get a hint for this ?

And , sorry for my english !!

1条回答
beautiful°
2楼-- · 2019-08-20 08:47

The timer can never fire whilst bJobDone == NO, this is because, NSTimers are added to the NSRunLoop and can only fire whilst waiting for an event.

查看更多
登录 后发表回答