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

尝试使用GCDwith调度请求dispatch_async,所以它变成

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

更新 a 的另一种方法UILabel是设置 aNSTimer每秒更新一次x(根据您的需要),而不是使用 a 循环while

那会是这样的

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不为零。如果是,那么过去更多的代码。

第一次评论后编辑:

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 回答