0

バックグラウンドで実行されているwhileステートメントがあります。

- (IBAction)startButton
{
 [self performSelectorInBackground:@selector(Counter) withObject:nil];
 .....
}

- (void) Counter 
{
  while (round) {
     if (condition)
     {
     NSString *str;
     str = [NSString stringWithFormat:@"%d",counter];
     [self performSelectorOnMainThread:@selector(updateLabel:) withObject:str waitUntilDone:NO];      
     }
  }
}
- (void)updateLabel: (NSString*) str
 {
[self.label setText:str];
NSLog(@"I am being updated %@",str);
 }

NSlog は正しい更新された値を取得しますが、ラベルは更新されません。

私は何を間違っていますか?

アップデート:

ラベルが接続され、while ステートメントが完了すると更新されます。

また、ラベルを初期化しました。

- (void)viewDidLoad
{   [super viewDidLoad];  
label.text = @"0";
}
4

3 に答える 3

2

Interface Builder で IBOutlet が接続されているかどうかを確認する

編集3

GCDwithdispatch_asyncを使用してリクエストをディスパッチしてみてください。

while (round) {
   if (condition)
   {
    NSString * str = [NSString stringWithFormat:@"%d",counter];
    dispatch_async(dispatch_get_main_queue(),^ {
      [self updateLabel:str];
    });
   }
}

a を更新する別の方法は、 a でループする代わりに、(必要に応じて) 秒ごとに更新する aUILabelを設定することです。NSTimerxwhile

それは次のようなものになります

NSTimer * updateLabelTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLabel) userInfo:nil repeats:YES];

-(void)updateLabel {
  if(condition) {
    self.label.text = [NSString stringWithFormat:@"%d", counter];
  }
}
于 2012-12-06T17:51:27.367 に答える
1

メイン スレッドは、バックグラウンド スレッドが終了するのを待っている可能性があります。バックグラウンド スレッドでどのようにタスクを開始しましたか?

于 2012-12-06T18:26:01.177 に答える
0

試す

dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), ^(void){
    [self updateLabel:str];
});

私はこれよりも好きperformSelectorOnMainThread:withObject:waitUntilDone:です。

役に立たない場合labelは、nil でないかどうかを確認してください。はいの場合は、さらにコードを過ぎてください。

最初のコメントの後に編集:

NSTimer役立つかもしれませんが、これもうまくいくはずです。

- (IBAction)startButton
{
    [self Counter];
}

- (void) Counter
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        while (round) {
            if (condition)
            {
                NSString *str;
                str = [NSString stringWithFormat:@"%d",counter];

                dispatch_async(dispatch_get_main_queue(), ^{
                    [self updateLabel:str];
                });
            }
        }

    });

}
- (void)updateLabel: (NSString*) str
{
    [self.label setText:str];
    NSLog(@"I am being updated %@",str);
}
于 2012-12-06T17:52:08.350 に答える