Reputation: 6176
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
Upvotes: 1
Views: 224
Reputation: 5539
I assume that score
property is a __block
type because you're changing it inside block in line:
score++;
because your block is executed with dispatch_async
main loop continues execution and most likely encounters score = newScore;
before your block even starts. When your block is about to run, score
is already equal newScore
and your loop's will never work, because its condition expression will return false. In:
for (int i=score; i< newScore; i++)
i
will equal to newScore
and because newScore < newScore
is false, your loop will never run.
I suggest to delete last line in your updateScore:
method.
score = newScore;
Upvotes: 2
Reputation: 16024
Your block is being executed asynchronously which means that the block executes in a new run loop ( = after you set score
to newScore
).
Upvotes: 2