str1の値を以下のように変化させた際、NSLog上では正常に10個の乱数が1秒ごとに表示されるのに、画面上に表示するchar.textは最後の1回分しか表示されません。10回分変化させ表示させるにはどうすればいいのでしょうか?
- (IBAction)B1:(id)sender {
for (demo=0;demo<10;demo++)
{
[NSThread sleepForTimeInterval:1];
up = arc4random() % 6 +1;
NSString *str1 = [NSString stringWithFormat:@"%d", up];
self.chara.text = str1;
NSLog(str1);
}
}
いろいろなやり方があると思いますが、待ちを入れる処理を別スレッドで動かすようにした場合にはこのような処理になると思います。
- (IBAction)B1:(id)sender { dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_queue_t mainQueue = dispatch_get_main_queue(); dispatch_async(globalQueue, ^{ for (demo=0;demo<10;demo++) { [NSThread sleepForTimeInterval:1]; up = arc4random() % 6 +1; dispatch_async(mainQueue, ^{ [self displayNumber:up]; }); } } } - (void)displayNumber:(int)up { NSString *str1 = [NSString stringWithFormat:@"%d", up]; self.chara.text = str1; NSLog(str1); }
大切なのは self.chara.text = str1; をしたときに、誰がどのタイミングで str1 の内容で画面を書き換えているかということの理解です。
一度、何かの書籍を通して読むことをお勧めします。