1

I'm doing a little game in Coco2D and I have a countdown clock Note: As I am just trying to fix a bug, I am not working on cleanup so the timer can stop, etc. Here is my code I'm using to setup the label and start the timer:

timer = [CCLabelTTF labelWithString:@"10.0000" fontName:@"Helvetica" fontSize:20]; 
        timerDisplay = timer;
        timerDisplay.position = ccp(277,310);
        [self addChild:timerDisplay];
        timeLeft = 10;

        timerObject = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];

Note: timeLeft is a double

This is updateTimers's code:

 -(void)updateTimer {
         NSLog(@"Got Called!");

         timeLeft = timeLeft -0.1;
     [timer setString:[NSString stringWithFormat:@"%f",timeLeft]];
       timerDisplay = timer;
         timerDisplay.position = ccp(277,310);
         [self removeChild:timerDisplay cleanup:YES];
         //[self addChild:timerDisplay];  
       if (timeLeft <= 0) {
             [timerObject invalidate];
         }     

     }

When I run this I toggle between crashing on this this: [timer setString:[NSString stringWithFormat:@"%f",timeLeft]]; and in the green arrow thing it gives Thread 1: EXEC_BAD_ACCESS (code=2, address=0x8) and 0x197a7ff: movl 16(%edi), %esi and in the green arrow thing it gives Thread 1: EXEC_BAD_ACCESS (code=2, address=0x8)

4

1 回答 1

0

看起来您的“计时器”(恕我直言,不是一个很好的文本对象名称)正在自动释放,因为它是使用便捷方法初始化的。因此,当您的计时器触发时,它可能会尝试操纵已释放的对象。有两种方法可以解决它:a。自己分配和初始化对象,或者 b. 向其添加“保留”消息,例如:

[[CCLabelTTF labelWithString:@"10.0000" fontName:@"Helvetica" fontSize:20] retain]; 

在这两种情况下,您将负责在您的 dealloc 或类似方法中释放对象,当您完成它时:

[timer release];
于 2012-06-10T23:03:33.520 回答