Would anyone know why the bmlabel is not updated? and the log “score” shows nothing? Without GCD, it works fine, but it blocks the ui (i would like to show the numbers between 100 to 500 for example, showing 101, 102…499, 500 very fast, instead of going directly from “100” to “500”). So i wanted to use another thread to calculate it, even if i’m not sure it’s the best way. Here’s my code :
//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;
}
Thanks a lot
I assume that
scoreproperty is a__blocktype because you’re changing it inside block in line:because your block is executed with
dispatch_asyncmain loop continues execution and most likely encountersscore = newScore;before your block even starts. When your block is about to run,scoreis already equalnewScoreand your loop’s will never work, because its condition expression will return false. In:iwill equal tonewScoreand becausenewScore < newScoreis false, your loop will never run.I suggest to delete last line in your
updateScore:method.