为什么这个计时器一次触发两次



> newsTimer每 35 秒触发一次,但它运行runNews 2 次。每次触发时,我都会获得 NSLog 设置runNews 2 次。

   -(id)init
{
    if ([super init]) {
        [self loadDefaults];
        NSTimer *newsTimer = [NSTimer scheduledTimerWithTimeInterval:35.0 target:self selector:@selector(runNews) userInfo:nil repeats:YES];
    }
    return self;
}

    -(void)runNews
{
    NSMutableArray *headingArray;
    if (_currentTips < 20) {
        headingArray = [NSMutableArray arrayWithObjects:@"Text 1", @"Text 2",
    }
    int randomGen = arc4random_uniform(headingArray.count - 1.0);
    NSString *headingString = [NSString stringWithString:headingArray[randomGen]];
    headingLabel = [[CCLabelTTF alloc] initWithString:headingString fontName:@"Minecraftia-Regular.ttf" fontSize:12.0];
    [headingLabel setPositionType:CCPositionTypeMake(CCPositionUnitPoints, CCPositionUnitPoints, CCPositionReferenceCornerTopRight)];
    [headingLabel setPosition:ccp(-200, 38)];
    [headingLabel setFontColor:([CCColor greenColor])];
    [self addChild:headingLabel];
    [headingLabel runAction:([CCActionMoveTo actionWithDuration:20.0 position:ccp(500, 38)])];
    NSLog(@"Running news");
    [headingLabel performSelector:@selector(removeFromParent) withObject:nil afterDelay:20.0];
}

我看不出任何理由为什么它会运行两次......有什么想法吗?

不确定为什么此方法运行两次(可能是 Hot Licks 建议的 2 个实例)。以下是我将如何构建它,以便很好地与 cocos2d 的调度和"单线程"配合使用。

又名,避免使用NSTimer和执行选择器。

您需要完全在 cocos2d 的运行循环、更新周期等中执行显示定义代码位,并避免修改主线程,以促进平滑渲染并避免抖动:

-(id)init
{
    if (self = ([super init]) {  // <=== did you forget to set self ?
        [self loadDefaults];
    }
    return self;
}
-(void) onEnter {
    [super onEnter];    // now this CCNode will be scheduled etc ...
    [self schedule:@selector(runNews) interval:35.0f]; // cocos will schedule this properly
}
-(void)runNews
{
    NSMutableArray *headingArray;
    if (_currentTips < 20) {
        headingArray = [NSMutableArray arrayWithObjects:@"Text 1", @"Text 2",
    }
    int randomGen = arc4random_uniform(headingArray.count - 1.0);
    NSString *headingString = [NSString stringWithString:headingArray[randomGen]];
    headingLabel = [[CCLabelTTF alloc] initWithString:headingString fontName:@"Minecraftia-Regular.ttf" fontSize:12.0];
    [headingLabel setPositionType:CCPositionTypeMake(CCPositionUnitPoints, CCPositionUnitPoints, CCPositionReferenceCornerTopRight)];
    [headingLabel setPosition:ccp(-200, 38)];
    [headingLabel setFontColor:([CCColor greenColor])];
    id move = [CCActionMoveTo actionWithDuration:20.0 position:ccp(500, 38)];
    id clean = [CCCallBlock actionWithBlock:^{
        NSLog(@"label %08X [%@] ends move.",(int) headingLabel,headingLabel.string);
        [headingLabel removeFromParentAndCleanup:YES];
    }];
    id seq = [CCActionSequence actions:move,clean,nil];
    [self addChild:headingLabel];
    NSLog(@"label %08X [%@] starts move.",(int) headingLabel,headingLabel.string);
    [headingLabel runAction:seq];
}

最新更新