为什么这个计时器一次点火两次?

时间:2014-12-24 02:38:57

标签: objective-c cocos2d-iphone

newsTimer每35秒触发一次,但会运行runNews 2次。每次激活时,我都会在runNews中设置2次NSLog。

   -(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];
}

我无法看到为什么会出现这种情况的任何原因......任何想法?

1 个答案:

答案 0 :(得分:0)

不确定此方法为何会运行两次(可能是Hot Licks建议的2个实例)。以下是我将如何构建这个,以便与cocos2d的调度和“单线程”一起很好地发挥作用

又名,避免使用NSTimer和performSelector。

你需要在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];
}