为什么我的 GCD 方法没有响应



有人知道为什么bmlabel没有更新吗? 日志"分数"什么也没显示?如果没有GCD,它可以正常工作,但它会阻塞UI(例如,我想显示100到500之间的数字,非常快速地显示101,102...499,500,而不是直接从"100"到"500")。所以我想使用另一个线程来计算它,即使我不确定这是最好的方法。这是我的代码:

//in .h, i imported :
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

//in .m
@implementation ScoreLayer
-(void)updateScore:(int)num{
    CCLOG(@"hello");
    int newScore = score+num;
    //dispatch_queue_t queue = dispatch_queue_create("Test", 0);
    dispatch_queue_t main = dispatch_get_main_queue();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        for (int i=score; i< newScore; i++){
            score++;
            CCLOG(@"score:%i", score);
            NSString *str = [NSString stringWithFormat:@"%d", score];
            dispatch_async(main, ^{
                [bmlabel setString:str];
            });
        }
    });
    score = newScore;
}
-(id) init
{
    if( (self=[super init])) {
        bmlabel = [CCLabelBMFont labelWithString:@"14763" fntFile:@"TestFont.fnt"];
        bmlabel.anchorPoint = ccp(0, 0.5f);
        bmlabel.position = ccp(0,250.0f);
        [self addChild:bmlabel z:200]; 
            score = 14763;
    }
    return self;
}

多谢

我假设score属性是__block类型,因为您要在行块内更改它:

 score++;

因为您的区块是用dispatch_async主循环继续执行的,并且很可能在您的区块开始之前遇到score = newScore;。当你的块即将运行时,score已经等于newScore并且你的循环将永远不会工作,因为它的条件表达式将返回 false。在:

for (int i=score; i< newScore; i++)

i等于newScore并且由于newScore < newScore为假,因此您的循环将永远不会运行。

我建议删除updateScore:方法中的最后一行。

score = newScore;

您的块正在异步执行,这意味着该块在新的运行循环中执行( = 在将score设置为 newScore 之后)。

最新更新