0

Below sample code never come out of while loop and its printing the number of running actions as 1 always. What I am missing?

Thanks in advance Krishna

-(id)init
{    
    if(self == [super init])
    {  
    CCSPrite *mySprt = [CCSprite spriteWithFile:@"myFile.png"];  
    mySprt.position = ccp(160,240);  
    mySprt.tag = 331; 
    CCFadeTo *fadeSprt = [CCFadeTo actionWithDuration:20.0 opacity:0];  
    [mySprt runAction:fadeSprt];  
    [self addChild:mySprt];  
    [self checkActionCount];
   }  
   return self;  

}

-(void)checkActionCount  
{  
while([self getchildByTag:331].numberofrunningactions > 0)  
    {  
     NSLog(@"Number of actions = %d",[self getchildByTag:331].numberofrunningactions);  
     continue;  
    }  
NSLog(@"Number of actions = %d",[self getchildByTag:331].numberofrunningactions);  
}
CodeSmile
  • 64,284
  • 20
  • 132
  • 217
SaffronState
  • 329
  • 1
  • 12

2 Answers2

1

You have an endless loop:

while([self getchildByTag:331].numberofrunningactions > 0)  
{  
     NSLog(..);  
     continue;
}  

The continue statement will exit the current block to re-evaluate the while condition, which is true, which will do a continue, and re-evaluate the while condition, and so on for all eternity.

Instead try this:

if ([self getchildByTag:331].numberofrunningactions > 0)  
{  
     NSLog(..);  
}  

and call the checkActionCount method from a scheduled selector, for instace update:, so that the condition is evaluated once every frame.

CodeSmile
  • 64,284
  • 20
  • 132
  • 217
  • Thanks Steffen. Yes you are right. This works now. But I am still not clear about why that loop doesnt break when the count becomes zero which is independent of the frame rate i guess. I assume that when an action completes then it will set the count to zero. And after iterating few times the while must break when the value is zero. Can you please help me in a bit detail. – SaffronState Mar 26 '14 at 16:21
  • You're blocking the thread with the endless while loop. So cocos2d'd state is frozen, hence no actions are updating, hence they will never advance let alone complete. That's why the condition never changes from true to false. – CodeSmile Mar 26 '14 at 16:32
  • Thanks again Steffen. I forgot the point that i am running while loop in main thread. And also seeing that cocos has already frozen i still couldn't got that point. – SaffronState Mar 26 '14 at 16:55
0
CCFadeTo *fadeSprt = [CCFadeTo actionWithDuration:20.0 opacity:0];      
[mySprt runAction:fadeSprt];  

You initialize a CCAction with duration 20.0 seconds. Now you run it on the mySprt. this increase the numberofRunningActions count by 1.

which is what you are checking in while loop and it logs 1. After 20 seconds when the action finishes. it will log 0 (unless you add other action).

Shubhank
  • 21,721
  • 8
  • 65
  • 83